Adding Styles to Built in Editor Templates in Razor

I thought I’d blog about this thing I keep forgetting the syntax for and I’m sick of Googling for it. It’s a bit of a niche thing in Razor. First, some background.

Previous to MVC 5, you could not add any styling to any of the built-in EditorTemplates. So, if you wanted to add a Bootstrap style to an input, you had to fall back on the simple Editor extension method:

@Html.EditorFor(m => m.Name, new { @class = "input-lg"}) // won't work
@Html.Editor ("Name", new { @class = "input-lg"}) // used to be OK - before MVC 5

The EditorTemplate would simply ignore the style. And if it happened to be the first time you bumped up against that foible, you probably blew half a day figuring out that it was not supported.

Someone whispered in Microsoft’s ear, because they changed this in MVC 5 (possibly the 5.1 release). The following syntax enables you to have your cake and eat it:

@Html.EditorFor(m => m.Name, new { HtmlAttributes = new { @class = "input-lg" }})

Note, you now have to use that new syntax with the simple Editor extension method as well.

Leave a Comment

NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>