1

I have a class with a property Password annotated as DataType.Password like this:

[DataType(DataType.Password)]
[Required]
public string Password { get; set; }

When I use EditorFor to show this field on the view, I need to apply a CSS class on it.

I do it the following way:

@Html.EditorFor(model => model.Password, "loginTextBox", new { @class = "form-control ", placeholder = "" })

For some reason there's no build-in way of using Html attributes for EditorFor() (like I could read here for example: Html attributes for EditorFor() in ASP.NET MVC), so I needed to create a simple EditorTemplate to allow it like this:

@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class = ViewData["class"], id = ViewData["id"], placeholder = ViewData["placeholder"]})

The problem is that, this editor is shared between other properties which are not DataType.Password. In the case the property is annotated as DataType.Password I want to use

@Html.Password(...)

otherwise

@Html.TextBox(...)

The only way I can think to achieve this is by checking the DataType, but I don't how to do that.

Any idea on how to check the DataType or even a better approach?

7
  • 1
    What version of asp.net MVC do you use? ASP.Net MVC 5 supports html attributes for EditorFor Commented Feb 25, 2014 at 14:30
  • You can write your own EditorTemplate for this purpose specifically. Commented Feb 25, 2014 at 14:31
  • That's not true #Murali. Check here: msdn.microsoft.com/en-us/library/… Commented Feb 25, 2014 at 14:32
  • #jacqijvv I know I could do a specific one, but then the Datatype.Password looses all its meaning. Commented Feb 25, 2014 at 14:33
  • 1
    @lpaloub, please check out the ASP.Net MVC 5.1 Release notes, @Html.EditorFor(model => model, new { htmlAttributes = new { @class = "form-control" }, }) Commented Feb 25, 2014 at 14:38

1 Answer 1

1

Now ASP.Net MVC 5.1 supports htmlAttributes for EditorFor. Just pass this as an anonymous object.

ASP.Net MVC 5.1 Release Notes

@Html.EditorFor(model => model.Password, "loginTextBox",
 new { htmlAttributes = new { @class = "form-control ", placeholder = ""})
Sign up to request clarification or add additional context in comments.

2 Comments

That might no be useful to everybody (not everybody can update), but since I was just starting the website this solution came perfect for me. Thanks again!
how can I use the Prompt metadata with the new EditorFor ?

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.