假设我有以下型号:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
public class Town
{
public string Name { get; set; }
public IEnumerable<Person> People { get; set; }
}
然后,在我的 Razor 视图中,我有这个:
@model Town
@using(Html.BeginForm())
{
<table>
@foreach(var person in Model.People)
{
<tr>
<td>@Html.TextBoxFor(m => person.Name)</td>
<td>@Html.TextBoxFor(m => person.Age)</td>
</tr>
}
<table>
<input type="submit" />
}
然后,我对 POST 进行了操作,如下所示:
[HttpPost]
public ActionResult Index(Town theTown)
{
//....
}
当我发布时,IEnumerable<Person>
不会遇到。如果我在 Fiddler 中查看它,该集合仅发布一次,并且不枚举该集合,所以我得到:
People.Name = "whatever"
People.Age = 99
但是,如果我将 People 更改为 anIList
并使用 for 循环而不是 foreach ......
@for(var i = 0;i < Model.People.Count;i++)
{
<tr>
<td>@Html.TextBoxFor(m => Model.People[i].Name)</td>
<td>@Html.TextBoxFor(m => Model.People[i].Age)</td>
</tr>
}
有用。难道我做错了什么?我错过了什么?