views:

135

answers:

1

HTML5 allows the use of custom attributes prefixed with the phrase "data-" which pass validation without the use of a custom DTD (more info). In Asp.Net MVC, is there any way to specify an ActionLink with a data- attribute?

The typical method for adding attributes to an ActionLink is to pass in an anonymous object, with a custom property for each object:

new { customattribute="value" }

What I'd like to do is:

new { data-customattribute="value" }

But this doesn't work, because the hyphen character isn't valid in property names. Is there any way around this restriction? Or do I just have to choose between using ActionLinks and using data- attributes?

+2  A: 

Yes, there is an overload for ActionLink method which takes an IDictionary<string,object> instead of an anonymous object.

<%=Html.ActionLink("text", "Index", "Home", null /*routeValues*/, 
    new Dictionary<string, object> { 
       { "data-customattribute", "value" }, 
       { "data-another", "another-value" } 
    })%>

Outputs :

<a data-another="another-value" data-customattribute="value" href="/">text</a>
çağdaş
Perfect. Note to future readers: If you use an IDictionary for the HTML attributes, you must also use a RouteDictionary for the routeValues parameter (you can use the same syntax as the HTML attributes use above).
AaronSieb