Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 3 Razor - Adding class to EditorFor

Adding a class to Html.EditorFor doesn't make sense as inside its template you could have many different tags. So you need to assign the class inside the editor template:

@Html.EditorFor(x => x.Created)

and in the custom template:

<div>
    @Html.TextBoxForModel(x => x.Created, new { @class = "date" })
</div>

As of ASP.NET MVC 5.1, adding a class to an EditorFor is possible (the original question specified ASP.NET MVC 3, and the accepted answer is still the best with that considered).

@Html.EditorFor(x=> x.MyProperty,
    new { htmlAttributes = new { @class = "MyCssClass" } })

See: What's New in ASP.NET MVC 5.1, Bootstrap support for editor templates


You can't set class for the generic EditorFor. If you know the editor that you want, you can use it straight away, there you can set the class. You don't need to build any custom templates.

@Html.TextBoxFor(x => x.Created, new { @class = "date" }) 

You can use:

@Html.EditorFor(x => x.Created, new { htmlAttributes = new { @class = "date" } })

(At least with ASP.NET MVC 5, but I do not know how that was with ASP.NET MVC 3.)