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:
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:
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:
All I have to do now is add the namespace to my page or web.config:
And then I can call the method inside my view:
Which gives me the same output as I get from the actionlink in ASP.NET MVC3:
That’s it for now. More on developing with ASP.NET MVC3, EF4 and mobile jQuery soon!
For other related information, check out these courses from Learning Tree: