9

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
  • 2
    Use a for loop (a foreach will not work) - refer this answer
    – user3559349
    Jul 5, 2016 at 14:19

2 Answers 2

21

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.

1
  • how about having two textboxes binded to two different properties.
    – Sana Ahmed
    Feb 13, 2019 at 5:00
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])
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.