I am looking at MVC3 razor examples and seeing html.editorfor being utilized and also asked about a lot on this forum. Why can't i use html.textboxfor
and passwordfor
? Thanks
The Html. Editor() or Html. EditorFor() extension methods generate HTML elements based on the data type of the model object's property.
The EditorFor() Helper is just like the TextBoxFor() Helper above with the exception that it will actually read metadata and other attributes from the Model to determine the appropriate type of element to render (such a checkbox for a boolean field) and it will map those values accordingly from the Model.
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.
EditorFor has the advantage that it will try to render an editor associated to the data type.
For example: If you design your own Editor Templates they will automatically be rendered based upon the property's type or UIHint
A useful editor template might be one that generates a date picker when the property's type is a DateTime
.
There are some other scenarios as well where the 'smart' EditorFor will generate the 'best' editor for the property such an example is when it renders a <textarea>
when tagging the property with MultilineText
Using TextBoxFor and PasswordFor are perfectly fine for those cases where you don't require 'a special editor'. It might even simplify your life when having to set HtmlAttributes.
Ref Differences between Html.TextboxFor and Html.EditorFor in MVC and Razor for clear the doubt about this..
The HtmlTextboxFor always creates a
textbox (<input type="text" ...).
While the EditorFor looks at the type and meta information, and can render another control or a template you supply.
For example for DateTime properties you can create a template that uses the jQuery DatePicker.
if you decide to change something to the aspect of how your textboxes are rendered like wrapping them in a div you could simply write a custom editor template (~/Views/Shared/EditorTemplates/string.cshtml)
and all your textboxes in your application will automatically benefit from this change whereas if you have hardcoded Html.TextBoxFor
you will have to modify it everywhere.
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