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

如何在ASP.NET MVC 5中从视图向控制器传递多个同模型对象?

ASP.NET MVC5 提交多组Person表单到控制器的解决方案

要实现多组Person表单提交,核心是让MVC模型绑定器识别出列表结构,关键步骤如下:

1. 创建视图模型

直接使用List<Person>作为视图模型不够直观,建议封装一个包含Person列表的视图模型:

public class PeopleViewModel
{
    public List<Person> People { get; set; } = new List<Person>();
}

2. 初始化视图模型(控制器GET方法)

在返回视图前,初始化视图模型中的People列表,预生成需要的空Person实例:

public ActionResult Index()
{
    var viewModel = new PeopleViewModel();
    // 初始化3组Person表单,可按需调整数量
    viewModel.People.Add(new Person());
    viewModel.People.Add(new Person());
    viewModel.People.Add(new Person());
    return View(viewModel);
}

3. 视图中用for循环生成表单字段

不能用foreach循环,因为foreach无法生成带索引的name属性,MVC模型绑定器无法识别为列表。改用for循环,通过索引访问集合元素,自动生成符合规范的name属性:

@model PeopleViewModel

@using (Html.BeginForm("PersonSave", "Home", FormMethod.Post, new { id = "PersonForm" }))
{
    <table>
        @for (int i = 0; i < Model.People.Count; i++)
        {
            <tr class="person-row">
                <td>Person @(i + 1)</td>
                <td>@Html.TextBoxFor(m => m.People[i].Name, new { @class = "form-control" })</td>
                <td>@Html.TextBoxFor(m => m.People[i].Age, new { @class = "form-control" })</td>
            </tr>
        }
        <tr>
            <td colspan="3">
                <button type="submit" class="btn btn-primary">保存</button>
                <!-- 可选:添加动态新增按钮 -->
                <button type="button" id="addPerson" class="btn btn-secondary">新增Person</button>
            </td>
        </tr>
    </table>
}

4. 控制器接收提交的数据

在POST方法中直接接收PeopleViewModel参数,模型绑定器会自动将表单数据组装成Person列表:

[HttpPost]
public ActionResult PersonSave(PeopleViewModel viewModel)
{
    // viewModel.People即为提交的多组Person数据,可直接用于业务处理
    // 示例:保存到数据库等操作
    return RedirectToAction("Index");
}

可选:动态新增表单字段

如果需要用户手动新增Person表单,可通过JavaScript生成带正确索引的字段:

$("#addPerson").click(function() {
    // 获取当前已有的Person行数作为新索引
    var index = $(".person-row").length;
    var newRow = `
        <tr class="person-row">
            <td>Person ${index + 1}</td>
            <td><input type="text" name="People[${index}].Name" class="form-control" /></td>
            <td><input type="text" name="People[${index}].Age" class="form-control" /></td>
        </tr>
    `;
    $("table").append(newRow);
});

关键说明

MVC模型绑定器识别列表的前提是表单字段的name属性格式为集合名[索引].属性名(如People[0].Name),for循环能自动生成这种格式,而foreach循环生成的name属性没有索引,无法被正确绑定。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 10:15:29