Adding attributes to HTML.EditorFor in MVC 5.1

I’ve been adding WAI-ARIA attributes to an ASP .NET MVC site lately (to enhance accessibility of the site) and it lead to some interesting research on how best to accomplish this.

One of the most prominent discussions is an MSDN blog entry from 2012 entitled “ASP.NET MVC: Adding aria-required attribute for required fields” by Stuart Leeks.

Stuart went into moredetail on supplying HTML attributes with EditorFor, and teamed up with his colleague Simon Ince to explain how to add HTML attributes in Templated Helpers such as EditorFor.

Fortunately, I found a better way thanks to a post on how to specify HTML Attributes in an EditorFor by AntonK on StackOverflow.com this December.  He also referenced the portion of the MVC 5.1 release notes where they explain that MVC now allows passing in HTML attributes in EditorFor as an anonymous object.

Here’s an example of how I used it to add an ARIA “aria=required” attribute:

@Html.EditorFor(model => model.City, new { htmlAttributes = new { @aria_required=”true” } })

@Html.ValidationMessageFor(model => model.City, “*”)

Note that the attribute is listed with an underscore, which MVC replaces with a hyphen.

I hope this helps!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s