ASP.NET MVC 3: Handling HTML 5 Attributes with Dashes




In versions prior to ASP.NET MVC 3, you could not declare HTML attributes with dashes/hyphens (like the custom data attribute in HTML 5), without creating a custom type that handled dashes for you. Most of you, who have used custom data attributes with dashes in MVC 1 and 2, must be familiar with the Compiler Error CS0746:

Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access

However in ASP.NET MVC 3, there is a trick that can be used to handle HTML attributes with dashes. Just use ‘underscores’ in your custom data attribute instead of ‘hyphens’. MVC 3 using the HTML helpers, automatically converts these underscores into dashes/hyphens

Here’s an example for you. Just declare an HTML attribute with an underscore separating two or more words, as shown below:

mvc3-html-dashes
When the page is rendered, this underscore is automatically converted by MVC 3 to an HTML attribute with dashes
mvc3 underscore to dashes
If you are interested in doing this in ASP.NET MVC 1 or 2, you just have to download the MVC 3 source code and see how is the HtmlHelper.AnonymousObjectToHtmlAttributes method implemented.

Here’s another tip about attributes that you may find useful ASP.NET MVC: Use CSS on Html.ActionLink


Will you give this article a +1 ? Thanks in advance




About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

2 Responses to "ASP.NET MVC 3: Handling HTML 5 Attributes with Dashes"
  1. Anonymous said...
    April 5, 2011 at 3:12 AM

    thanks for the tip on AnonymousObjectToHtmlAttributes method. It will come handy in our project

  2. Anonymous said...
    June 7, 2011 at 5:52 PM

    Very, very helpful post. You saved me from completely tearing my hair out over an otherwise very confusing error. Thank you!

 

Copyright © 2009-2014 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions