razor – ASP.NET MVC 4 – for循环帖子模型集合属性,但foreach不

我有以下型号:
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; }
}

然后,在我的剃刀视图中,我有这:

@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更改为IList并使用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>
}

有用。我做错了什么?我缺少什么?

解决方法

问题不是与IEnumerable或IList它是你的视图中呈现集合的方式。
@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>
}

注意,每个列表项目都附加一个连续的索引,这使得模型绑定器能够做到它的魔力

A good read

相关文章

这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识...
Some samples are below for ASP.Net web form controls:(fr...
问题描述: 对于未定义为 System.String 的列,唯一有效的值...
最近用到了CalendarExtender,结果不知道为什么发生了错位,...
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence cha...