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; }

}

然后,在我的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更改为an 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>

}

有用。难道我做错了什么?我错过了什么?


UYOU
浏览 572回答 3
3回答

30秒到达战场

这个问题是不是与IEnumerable或者IList它正进行渲染集合视图的方式。@for(var i = 0;i < Model.People.Count;i++){&nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; &nbsp; <td>@Html.TextBoxFor(m => Model.People[i].Name)</td>&nbsp; &nbsp; &nbsp; &nbsp; <td>@Html.TextBoxFor(m => Model.People[i].Age)</td>&nbsp; &nbsp; </tr>}观察每个列表项,您附加一个连续索引,使模型绑定器能够发挥其魔力

慕容708150

这是正常行为。模型绑定器使用呈现的html中的输入元素的name属性。使用与一个索引循环是有模型绑定可以关联到模型的唯一名称的唯一途径&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP