ASP.NET MVC 4 - 循环posts模型集合属性的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&LT;&人GT;
不会在来。如果我看它的提琴手,收集岗位只有一次,不枚举集合,所以我得到:
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
但是,如果我改变了人们一个的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 - 循环posts模型集合属性的foreach,但不的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!