Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using HTML.TextBoxFor to loop through items in a model [duplicate]

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.

like image 599
Bohn Avatar asked Jul 05 '16 14:07

Bohn


People also ask

What is the difference between HTML textbox vs HTML TextBoxFor?

IMO the main difference is that Textbox is not strongly typed. TextboxFor take a lambda as a parameter that tell the helper the with element of the model to use in a typed view. You can do the same things with both, but you should use typed views and TextboxFor when possible.

What is difference between EditorFor and TextBoxFor in MVC?

TextBoxFor: It will render like text input html element corresponding to specified expression. In simple word it will always render like an input textbox irrespective datatype of the property which is getting bind with the control. EditorFor: This control is bit smart.

What is TextBoxFor in MVC?

TextBoxFor represents a single-line input control that allows end-users to enter text.

How do you make a TextBoxFor ReadOnly?

The TextBoxes can be made ReadOnly by setting the HTML ReadOnly attribute using the HtmlAttributes parameter in Html.


1 Answers

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.

like image 138
Georg Patscheider Avatar answered Oct 19 '22 23:10

Georg Patscheider