将模型发布到控制器时,模型内的List属性为null

时间:2014-08-17 22:04:51

标签: c# asp.net-mvc-3

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

我的模型如下:

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

员工再次成为典范:

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视为null。

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

2 个答案:

答案 0 :(得分:1)

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

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>
}

答案 1 :(得分:1)

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

当您使用[Bind(Prefix="employeeList")]时,您告诉ModelBinder剥离&#34; employeeList&#34;从发回的每个媒体资源的名称的开头开始,代替employeeList[0].IdemployeeList[0].Name(这是您的回复class EmployeeList的正确),您获得{{1 }和[0].Id(但[0].Name没有属性class EmployeeListId

如果您使用该属性,则需要将参数更改为

Name

将正确绑定