Using HTML.TextBoxFor to loop through items in a m

2019-06-25 04:35发布

This question already has an answer here:

Probably a stupid question but I am new to MVC.

So far in my Razor I could say @HTML.TextBoxFor(t => t.EmailAddress) but now I have a for-each:

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

I asked my question in the code sample above. So when I am inside a for-each loop how can I can use @HTML.TextBox ? because now it doesn't get the lambda syntax anymore.

2条回答
Rolldiameter
2楼-- · 2019-06-25 05:09

Do not use foreach, because this will cause problems when you try to bind your inputs back to the model. Instead use a for loop:

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

See also Model Binding to a List MVC 4.

查看更多
Emotional °昔
3楼-- · 2019-06-25 05:13

You'll have to use a for loop to accomplish this as you'll need the actual index of the element to bind to the name attribute, which is used to ensure that your values are properly posted to the server :

@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])
}
查看更多
登录 后发表回答