lpaloub
lpaloub

Reputation: 868

Html Attributes on EditorFor() or Check dataType in EditorTemplate

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?

Upvotes: 1

Views: 1659

Answers (1)

Murali Murugesan
Murali Murugesan

Reputation: 22619

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 = ""})

Upvotes: 1

Related Questions