8

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.

Bohn
  • 26,091
  • 61
  • 167
  • 254
  • 2
    Use a `for` loop (a `foreach` will not work) - [refer this answer](http://stackoverflow.com/questions/30094047/html-table-to-ado-net-datatable/30094943#30094943) –  Jul 05 '16 at 14:19

2 Answers2

20

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.

Community
  • 1
  • 1
Georg Patscheider
  • 9,357
  • 1
  • 26
  • 36
5

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])
}
Rion Williams
  • 74,820
  • 37
  • 200
  • 327