使用原生JS提交表单时数据无法传递到Controller的问题排查
问题根因
表单提交后后端收不到数据的核心原因是你所有的<input>标签只配置了id属性,没有配置name属性。浏览器提交表单时,只会把带有name属性的字段以name=value的格式组装到请求体中,没有name的字段会被直接忽略,后端自然拿不到任何数据。
另外还有两个潜在问题会影响提交逻辑:
- 触发函数的
<button>标签没有指定type属性,浏览器会默认将其识别为提交按钮,可能触发非预期的默认表单提交行为,干扰你写的自定义提交逻辑 - JS中直接使用Razor输出的
@ViewBag数值做计算时没有做类型转换,可能出现字符串拼接的逻辑错误
修复方案
1. 给所有表单字段补充name属性
name属性的值需要和你后端Controller接收参数的字段名(或实体类属性名)完全一致,拼写、大小写不要有偏差,参考修改:
<form action="RetailTimePriceDisplayOne" method="post" id="postForm" name="postForm"> <input type="text" id="fmZero" name="zero" value="@ViewBag.zero" /> <input type="text" id="fmVehicle" name="vehicleType" /> <input type="text" id="fmTeam" name="teamCount" /> <input type="text" id="fmTLabor" name="travelLabor" /> <input type="text" id="fmRouteCost" name="routeCost" /> <input type="text" id="fmRouteD" name="vehicleMile" value="@ViewBag.vehicleMile"/> <input type="text" id="fmRouteT" name="vehicleTime" value="@ViewBag.vehicleTime"/> </form>
注意:上面代码里的
name属性值请替换成你后端实际定义的接收参数名,保证前后端字段名一一对应才能完成数据绑定。
2. 给触发按钮添加type="button"属性
修改按钮代码,屏蔽浏览器默认的提交行为,只触发你绑定的onclick自定义逻辑:
<button type="button" class="btn btn-secondary btn-lg" style="width:100%; height:100%;" onclick="fillForm('T',3)"> <strong>@ViewBag.TrkThr</strong> <p>with 3 persons</p> <p>+ @ViewBag.TrkMinute per labor minute*</p> </button>
3. (可选优化)修复JS数值计算的类型问题
给JS中用到的@ViewBag数值加上显式类型转换,避免出现字符串拼接的计算错误,参考修改:
function fillForm(vehicleType, teamCount, travelLabor, routeCost) { document.getElementById("fmVehicle").value = vehicleType; document.getElementById("fmTeam").value = teamCount; var x = Number(@ViewBag.rateTravelDrvr); if (teamCount > 1) { x = Number(@ViewBag.rateTravelDrvr) + (Number(@ViewBag.rateTravelCrew) * (teamCount - 1)); } document.getElementById("fmTLabor").value = x; var y; if (vehicleType == "V") { y = Number(@ViewBag.vVPrice); } if (vehicleType == "H") { y = Number(@ViewBag.vHPrice); } if (vehicleType == "T") { y = Number(@ViewBag.vTPrice); } document.getElementById("fmRouteCost").value = y; SubmitForm(); }
改完之后再测试,打开浏览器开发者工具看网络请求的Payload部分,就能看到所有表单字段都正常携带了,后端也能正常接收数据。
内容的提问来源于stack exchange,提问作者Nick Fleetwood
相关产品推荐
相关产品推荐

