7

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?

2
  • What do you mean by overwrites the HTML attributes? Commented Mar 22, 2013 at 9:49
  • 1
    @mosquito :What is your question actually? If you want required field validation you can set it in the model. Commented Mar 22, 2013 at 9:53

2 Answers 2

10

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.

Sign up to request clarification or add additional context in comments.

2 Comments

So what did the OP mean by overwrites the HTML attributes?
@MichaelPerrenoud, why are you asking me? Ask the OP. I guess what he meant is that the new { required = "required" } parameter he was passing to the editor template had no effect whatsoever which is perfectly normal because the default editor template built-in ASP.NET MVC doesn't use them. That's why I suggested to create a custom editor template that will use those parameters.
-1

Not sure it's an option but you could just put [Required] as a property decorator on the Model.

1 Comment

No, this has no effects on the html attribute I want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.