I am trying to use HTML5 data- attributes in my ASP.NET MVC 1 project. (I am a C# and ASP.NET MVC newbie.)
<%= Html.ActionLink("« Previous", "Search",
new { keyword = Model.Keyword, page = Model.currPage - 1},
new { @class = "prev", data-details = "Some Details" })%>
The "data-details" in the above htmlAttributes give the following error:
CS0746: Invalid anonymous type member declarator. Anonymous type members
must be declared with a member assignment, simple name or member access.
It works when I use data_details, but I guess it need to be starting with "data-" as per the spec.
My questions:
- Is there any way to get this working and use HTML5 data attributes with Html.ActionLink or similar Html helpers ?
- Is there any other alternative mechanism to attach custom data to an element? This data is to be processed later by JS.
In mvc 4 Could be rendered with Underscore(" _ ")
Razor:
Rendered Html
You can implement this with a new Html helper extension function which will then be used similarly to the existing ActionLinks.
And you call it like so ...
Simples :-)
edit
bit more of a write up here
This problem has been addressed in ASP.Net MVC 3. They now automatically convert underscores in html attribute properties to dashes. They got lucky on this one, as underscores are not legal in html attributes, so MVC can confidently imply that you'd like a dash when you use an underscore.
For example:
will render this in MVC 3:
If you're still using an older version of MVC, you can mimic what MVC 3 is doing by creating this static method that I borrowed from MVC3's source code:
And then you can use it like this:
and this will render the correct data-* attribute:
I do not like use pure "a" tag, too much typing. So I come with solution. In view it look
Implementation of Dic class
You can use it like this:
In Mvc:
In Html:
I ended up using a normal hyperlink along with
Url.Action
, as in:It's uglier, but you've got a little more control over the
a
tag, which is sometimes useful in heavily AJAXified sites.HTH