Using HTML.TextBoxFor to loop through items in a m

2019-06-25 05:21发布

问题:

This question already has an answer here:

  • Post an HTML Table to ADO.NET DataTable 2 answers

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.

回答1:

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.



回答2:

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])
}