【发布时间】:2014-08-17 22:04:51
【问题描述】:
我正在创建一个基本的 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 为 null。
如果我遗漏了什么,请帮助我。 提前致谢。
【问题讨论】:
标签: c# asp.net-mvc-3