You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET MVC Html.BeginForm提交时Controller接收列表数据错误

问题根因

提交后列表绑定失败是以下几个代码错误共同导致的:

  • 表单字段name属性前缀和Controller接收参数名不匹配:JS动态生成输入框时用的前缀是studentModels[索引],但Controller接收的列表参数名是s,MVC默认模型绑定严格按参数名匹配前缀,前缀不一致无法完成绑定。
  • 动态生成的Age输入框属性写错:给Age字段加的是Age="xxx"属性,不是表单提交必需的name="xxx"属性,没有name属性的输入框值根本不会随表单提交到后端。
  • 索引冲突:JS初始计数count=0,但Razor默认渲染的第一行输入框已经占用了索引0,动态生成的第一条数据索引重复,导致绑定异常。
  • Razor语法错误:把HTML标签、HtmlHelper输出代码错误包裹在C#代码块@{}中,且tbody标签未正确闭合,HTML结构异常。
  • 代码笔误:Controller中ViewBag被错写为ViewBad,初始输入框id重复使用Name/Age,引发DOM选择异常。
修复方案

1. 修正Controller代码

修正笔误,保持列表参数名为s即可:

[HttpPost]
public ActionResult Form(List<Student> s)
{
    ViewBag.Items = s.Count;
    ViewBag.Value = s[0].Age;
    return View("Index");
}

2. 修正View层Razor代码

移除错误的C#代码块包裹,修正HTML结构,调整初始输入框id避免重复:

@model List<MVCModel.Models.Student>

<b>Items</b> @ViewBag.Items <br />
<b>Value</b> @ViewBag.Value <br />
  
@using (Html.BeginForm("Form", "Home", FormMethod.Post))
{
<table>
    <tbody id="GenaratorList">
        <tr>
            <td>Enter Name: </td>
            <td>@Html.TextBoxFor(m => m[0].Name, new {id = "inputName"})</td>
            <td>Enter Age: </td>
            <td>@Html.TextBoxFor(m => m[0].Age, new {id = "inputAge"})</td>
            <td><input type="button" value="Add" onclick="addGenarator()" /></td>
        </tr>
    </tbody>
</table>
<input type="submit" value="Submit Form"/>
}

3. 修正前端JS逻辑

统一输入框name前缀和后端参数名一致,修正Age字段的属性名,调整索引起始值避免冲突:

// 初始已存在索引0的输入行,新增项从索引1开始计数
let count = 1;
function addGenarator() {
    const nameVal = $('#inputName').val();
    const ageVal = $('#inputAge').val();
    // name前缀必须和后端List参数名s完全一致,格式为 s[索引].属性名
    const prefix = `s[${count}]`;
    $('#GenaratorList').append(`
        <tr>
            <td>
                <input id="${prefix}_Name" name="${prefix}.Name" type="text" class="form-control" readonly value="${nameVal}">
            </td>
            <td>
                <input id="${prefix}_Age" name="${prefix}.Age" type="text" class="form-control" readonly value="${ageVal}">
            </td>
        </tr>
    `);
    // 清空输入框
    $('#inputName,#inputAge').val('');
    count++;
}

补充说明:MVC默认模型绑定要求列表索引从零开始连续不中断,当前新增逻辑符合该要求。如果后续需要支持删除行功能,需要额外为每一行添加<input type="hidden" name="s.Index" value="对应索引值" />指定索引,否则删除中间行后索引断裂会再次出现绑定失败问题。

内容的提问来源于stack exchange,提问作者dap

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 14:27:18