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.
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.
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.
TextBoxFor represents a single-line input control that allows end-users to enter text.
The TextBoxes can be made ReadOnly by setting the HTML ReadOnly attribute using the HtmlAttributes parameter in Html.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With