使用HTML.TextBoxFor循环遍历模型中的项目

Boh*_*ohn 4 c# asp.net-mvc razor

可能是一个愚蠢的问题,但我是MVC的新手.

到目前为止,在我的剃刀中,我可以说,@HTML.TextBoxFor(t => t.EmailAddress) 但现在我有一个for-each:

foreach(var q in Model.Questions)
{
  // so here the t => t.EmailAddress  syntax is not working anymore.
}
Run Code Online (Sandbox Code Playgroud)

我在上面的代码示例中问了我的问题.因此,当我在for-each循环中时,我该如何使用@HTML.TextBox ?因为现在它不再获得lambda语法.

Geo*_*der 13

不要使用foreach,因为当您尝试将输入绑定回模型时,这会导致问题.而是使用for循环:

for (var i = 0; i < Model.Questions.Count(); i++) {
    @Html.TextBoxFor(m => m.Questions[i])
}
Run Code Online (Sandbox Code Playgroud)

另请参见模型绑定到列表MVC 4.


Rio*_*ams 5

您将需要使用for循环来完成此操作,因为您需要将元素的实际索引绑定到name属性,该索引用于确保将值正确发布到服务器:

@for (var q = 0; i < Model.Questions.Count(); q++) { 
    // This will bind the proper index to the appropriate name attribute
    @Html.TextBoxFor(x => x.Questions[q])
}
Run Code Online (Sandbox Code Playgroud)