当将模型提交给控制器时,模型中的List属性将变为null

本文关键字:模型 属性 List null 提交 控制器 | 更新日期: 2023-09-27 18:18:18

我正在创建一个基本的mvc3应用程序,其中我试图将具有列表属性(模型类型)的复杂模型类型发布到我的控制器。但当我这样做时,该属性将在模型中作为null。

我的模型如下:

public class EmployeeList
{
    public List<Employee> employeeList { get; set; }
}

Employee又是一个模型:

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
}

控制器代码为:

[HttpGet]
public ActionResult Index()
{
    EmployeeList em = new EmployeeList();
    em.employeeList = new List<Employee>() { new Employee(){}};
    return View(em);
}
[HttpPost]
public ActionResult Index([Bind(Prefix = "employeeList")]EmployeeList employeeList1)
{
    .......
}

和视图如下:

Index.cshtml: -

@model test.Models.EmployeeList
@{
    ViewBag.Title = "Index";
 }
<h2>Index</h2>
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { @id = "testForm" }))
{
    @Html.LabelFor(m => m.eid)
    @Html.EditorFor(m => m.eid)
    @Html.HiddenFor(m => m.eid)
    <br />
    @Html.EditorFor(x => x.employeeList)
    <br />
    <p>
        <input type="submit" value="Post" />
    </p>
}

编辑器模板视图是:

@model test.Models.Employee
@Html.LabelFor(model => model.Id)
@Html.TextBoxFor(model => model.Id)
@Html.HiddenFor(model => model.Id)
<br />
<br />
@Html.LabelFor(model => model.Name)
@Html.TextBoxFor(model => model.Name)
@Html.HiddenFor(model => model.Name)

在我检查的浏览器上,名称和id的生成如下:

name="employeeList[0].Id", id="employeeList_0__Id"
name="employeeList[0].Name", id="employeeList_0__Name"

但是当我将这个EmployeeList模型发布到控制器时,我得到的EmployeeList为空。

请帮助我,如果我错过了什么。

当将模型提交给控制器时,模型中的List属性将变为null

我认为mvc模型绑定可能会变得混乱。尝试将模型的属性名称从employeeList更改为ListOfEmployees。例如

public class EmployeeList
{
    public List<Employee> ListOfEmployees { get; set; }
}
[HttpPost]
public ActionResult Index([Bind(Prefix = "ListOfEmployees")]EmployeeList employeeList1)
{
    .......
}
@model test.Models.EmployeeList
@{
    ViewBag.Title = "Index";
 }
<h2>Index</h2>
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { @id = "testForm" }))
{
    @Html.LabelFor(m => m.eid)
    @Html.EditorFor(m => m.eid)
    @Html.HiddenFor(m => m.eid)
    <br />
    @Html.EditorFor(x => x.ListOfEmployees)
    <br />
    <p>
        <input type="submit" value="Post" />
    </p>
}

正如您所发现的,您需要删除BindAttribute。解释:

当您使用[Bind(Prefix="employeeList")]时,您告诉ModelBinder从发布回来的每个属性的名称开头剥离"employeeList",因此,而不是employeeList[0].IdemployeeList[0].Name(这是正确的,因为您的发布回class EmployeeList),您得到[0].Id[0].Name(但class EmployeeList没有属性IdName

如果您像以前那样使用属性,则需要将参数更改为

public ActionResult Index([Bind(Prefix = "employeeList")]List<Employee> employeeList1)

可以正确绑定