How to use HTML5 data-* in ASP.NET MVC 2

In my last post, I gave a couple of tips on working with ASP.NET MVC and HTML5. The only problem was, one of the tips – substituting underscores for hyphens in HTML5 data-* attributes – only works if you’ve upgraded to ASP.NET MVC 3. That got me thinking about the best way to handle data-* attributes in older versions of ASP.NET MVC.  As It turned out that was a really good thing to do, as I found I needed it when created an HtmlHelper that built links – so

Here’s the problem: attributes are supplied to the actionlink helper as properties of an anonymous object, and property names can’t contain hyphens.

The solution in ASP.NET MVC 3 is to substitute underscores, and the actionlink helper converts them to hyphens.

Here’s a solution for ASP.NET MVC 2: write an extension method to convert the _ in attributes to -.

I wrote an extension method for the HtmlHelper class that accepted text for the link, a routevalues object and an anonymous object to hold the HTML attributes. Note that the method is returning an MvcHtmlString rather than a string – otherwise, your HTML is encoded when it’s written into the page, leading to the HTML being displayed rather than interpreted:

signature of the extension method

Inside the method, I created a TagBuilder and started to build the <a> tag. Most of it is fairly straight-forward, e.g. using a UrlHelper to create the link:

using the UrlHelper

The difficulty comes when you have to work with the htmlAttributes anonymous object. It’s not a collection, so you can’t just enumerate through it. You have to use reflection instead. Here, I get the type, then the properties – then iterate through the properties and use a string.Replace() to generate the correct string name for the attribute. I then combine the corrected attribute string with the  value of the property:

using reflection with the anonymous object

All I have to do now is add the namespace to my page or web.config:

importing the namespace

And then I can call the method inside my view:

calling the new helper

Which gives me the same output as I get from the actionlink in ASP.NET MVC3:

the html output

the visual output

That’s it for now. More on developing with ASP.NET MVC3, EF4 and mobile jQuery soon!

Kevin Rattan

For other related information, check out these courses from Learning Tree:

Building Web Applications with ASP.NET MVC

jQuery: A Comprehensive Hands-On Introduction

HTML5: Next Generation Web Development

Type to search blog.learningtree.com

Do you mean "" ?

Sorry, no results were found for your query.

Please check your spelling and try your search again.