Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC3 why use html.editorfor

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

like image 522
learning... Avatar asked Apr 21 '12 03:04

learning...


People also ask

What is the use of HTML EditorFor?

The Html. Editor() or Html. EditorFor() extension methods generate HTML elements based on the data type of the model object's property.

What is the difference between TextBoxFor and EditorFor?

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.

What is difference between HTML textbox and 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.


2 Answers

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.

like image 181
Philip Fourie Avatar answered Sep 22 '22 23:09

Philip Fourie


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.

like image 32
Niranjan Singh Avatar answered Sep 25 '22 23:09

Niranjan Singh