ASP.NET MVC Html.BeginForm提交List到Controller始终为null
问题原因
你的代码一共存在4个直接导致模型绑定失败、后端接收到null的问题:
- 表单字段名前缀和Controller Action的参数名不匹配:ASP.NET MVC 默认模型绑定规则要求,集合类型参数的表单字段
name属性前缀必须和Action的形参名完全一致。你的Action形参是List<Student> s,但JS动态生成的输入框前缀写的是studentModels[count],前缀和参数名s完全不匹配,绑定器无法识别这些字段属于目标参数(如果不想改JS前缀,也可以给Action参数加[Bind(Prefix = "studentModels")]特性指定绑定前缀,两种方式二选一即可)。 - 动态生成的年龄输入框缺少
name属性:你写年龄输入框的HTML字符串时,误将name属性写成了Age属性,表单提交时只会采集带合法name属性的控件值,Age字段没有name属性,值根本不会被发送到后端。 - HTML标签结构错误:表格的
<tbody>标签没有正确闭合,写了两个<tbody>开标签,缺少对应的闭合标签</tbody>,异常的DOM结构可能导致表单提交时字段采集异常。 - 顶部初始输入框的字段名不符合集合绑定规则:初始用于录入的Name、Age输入框是用
Html.TextBoxFor生成的,name属性是单独的Name、Age,不属于集合索引格式,这部分值不会被绑定到List<Student>类型参数上(你当前逻辑是点Add按钮才把值转成动态行,这部分逻辑本身没问题,但要注意必须点Add把值加入动态行后再提交)。
修复方案
- 把JS中生成动态输入框的字段前缀从
studentModels[count]改成和Action参数名一致的s[count],或者给Action参数加绑定前缀特性匹配JS的命名 - 修正年龄输入框的属性,把错误的
Age=改成name= - 修正tbody标签的闭合错误
- (可选)给Add按钮加非空校验、提交时判断是否有添加学生行,避免无效提交
修复后的完整代码
View 代码
@model MVCModel.Models.Student <b>Result</b> @ViewBag.s <br /> @using (Html.BeginForm("Form", "Home", FormMethod.Post)) { <table> <tbody id="GenaratorList"> <tr> <td>Enter Name: </td> <td>@Html.TextBoxFor(m => m.Name)</td> <td>Enter Age: </td> <td>@Html.TextBoxFor(m => m.Age)</td> <td><input type="button" value="Add" onclick="addGenarator()" /></td> </tr> </tbody> <!-- 修正原代码错误的tbody开标签为闭合标签 --> </table> <input type="submit" value="Submit Form"/> } <script> count = 0; function addGenarator() { var Name = $('#Name').val(); var Age = $('#Age').val(); if(!Name || !Age){ alert('请先输入姓名和年龄'); return; } // 前缀改为和Action参数名一致的s var studentRow = "s[" + count + "]"; // 修正Age输入框的name属性,原代码误写为Age= $('#GenaratorList').append('<tr><td><input id="' + studentRow + '.Name" name="' + studentRow + '.Name" type="text" class="form-control" readonly value="' + Name + '"></td><td><input id="' + studentRow + '.Age" name="' + studentRow + '.Age" type="text" class="form-control" readonly value="' + Age + '"></td></tr>'); $('#Name,#Age').val(''); count++; } </script>
Controller 代码
[HttpPost] public ActionResult Form(List<Student> s) { // 增加判空逻辑避免空引用异常 if(s != null && s.Any()){ ViewBag.s = $"成功提交{s.Count}条学生数据"; } return View("Index"); }
Model 代码(无需改动,保持原有逻辑即可)
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MVCModel.Models { public class Student { public string Name { get; set; } public int Age { get; set; } } }
修复后测试:输入姓名年龄点Add添加多行,提交后后端就能正常接收到完整的
List<Student>集合,不会再出现null值触发空引用的问题。
内容的提问来源于stack exchange,提问作者dap
相关产品推荐
相关产品推荐

