Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Html(5) attributes for EditorFor

I know this has been discussed a lot of times.

I'd like to use

@Html.EditorFor(u => u.Password, new { required = "required" })

Unfortunatley this isn't possible by default as the EditorFor overwrites the Html attributes.

I don't want to use TextBoxFor because I'd like the value to be formatted according to the DisplayFormat attribute.

Is there any solution for this?

like image 579
mosquito87 Avatar asked Mar 22 '13 09:03

mosquito87


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 are the advantages of the HTML EditorFor () method?

The advantages of EditorFor is that your code is not tied to an <input type="text" . So 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.

What is HTML DisplayFor?

DisplayFor() The DisplayFor() helper method is a strongly typed extension method. It generates a html string for the model object property specified using a lambda expression.


1 Answers

You could write a custom editor template for the string type (~/Views/Shared/EditorTemplates/string.cshtml):

@Html.TextBox(
    "", 
    ViewData.TemplateInfo.FormattedModelValue,
    ViewData
)

and then:

@Html.EditorFor(u => u.Password, new { required = "required" })

will work as expected.

like image 136
Darin Dimitrov Avatar answered Nov 03 '22 00:11

Darin Dimitrov