How to add custom data attributes and classes to `@Html.EditorFor`?

Martinffx picture Martinffx · Jul 19, 2013 · Viewed 21.5k times · Source

I want to add some custom attributes to the input generated by @Html.EditorFor, I tried the following:

@Html.EditorFor(model => model.Percent, new { @class = "percent" })

But it just ignores my class, from what I can tell from searching around is that the template doesn't support adding custom attributes.

But how does one create a custom template adding support for the custom attributes, while keeping all the functionality of the old template?

Answer

Praveen M P picture Praveen M P · Nov 22, 2013

Using jQuery this could be done easily

$("input").addClass("class-name")

Input tag

@Html.EditorFor(model=>model.Name)

For DropDownlist u can use following code

$("select").addClass("class-name")

for Dropdownlist

@Html.DropDownlistFor(model=>model.Name)