ASP.NET MVC 4 - for 循环发布模型集合属性但 foreach 没有 [英] ASP.NET MVC 4 - for loop posts model collection properties but foreach does not
问题描述
假设我有以下模型:
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 视图中,我有这个:
Then, in my Razor view, I have this:
@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 操作,如下所示:
Then, I have an action for the POST, something like this:
[HttpPost]
public ActionResult Index(Town theTown)
{
//....
}
当我发布时,IEnumerable
没有出现.如果我在 Fiddler 中查看它,该集合仅发布一次,并且不会枚举该集合,因此我得到:
When I post, the IEnumerable<Person>
does not come across. If I look at it in Fiddler, the collection only posts once, and doesn't enumerate the collection, so I get:
People.Name = "whatever"
People.Age = 99
但是,如果我将 People 更改为 IList
并使用 for 循环而不是 foreach...
However, if I change People to an IList
and use a for loop instead of a 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>
}
它有效.难道我做错了什么?我错过了什么?
It works. Am I doing something wrong? What am I missing?
推荐答案
问题不在于 IEnumerable
或 IList
它是您呈现集合的方式你的看法.
the problem is not with the IEnumerable
or the IList
it the way you are rendering the collection in your view.
@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>
}
请注意,对于每个列表项,您都附加了一个连续索引,这使模型绑定器能够发挥其魔力
Observe that with each list item you are appending a continuous index which enables the model binder to do its magic
这篇关于ASP.NET MVC 4 - for 循环发布模型集合属性但 foreach 没有的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!