I tried to use in my ASP.NET MVC 1 project HTML5 data properties . (I'm new to C and ASP.NET MVC.)
<%= Html.ActionLink("« Previous", "Search", new { keyword = Model.Keyword, page = Model.currPage - 1}, new { @class = "prev", data-details = "Some Details" })%>
The "data details" in the htmlAttributes above gives 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 think it needs to start with "data -" according to the specification.
My question:
- Is there a way to make this work and use HTML5 data properties with Html.ActionLink or similar Html helper?
- Is there another alternative mechanism for attaching custom data to elements? This data will be processed later by JS.
#1 building
It's easier than all of the above. The data properties in MVC that contain dashes (-) are satisfied by the use of underscores ().
<%= Html.ActionLink("« Previous", "Search", new { keyword = Model.Keyword, page = Model.currPage - 1}, new { @class = "prev", data_details = "Some Details" })%>
I see that Johnny o has already mentioned that.
#2 building
Update: support for this is built into MVC 3 and later. For recommended solutions, see the highly rated answers from Johnny o below.
I don't think there is any direct help to achieve this, but I have two ideas for you to try:
// 1: pass dictionary instead of anonymous object <%= Html.ActionLink( "back", "Search", new { keyword = Model.Keyword, page = Model.currPage - 1}, new Dictionary<string,Object> { {"class","prev"}, {"data-details","yada"} } )%> // 2: pass custom type decorated with descriptor attributes public class CustomArgs { public CustomArgs( string className, string dataDetails ) { ... } [DisplayName("class")] public string Class { get; set; } [DisplayName("data-details")] public string DataDetails { get; set; } } <%= Html.ActionLink( "back", "Search", new { keyword = Model.Keyword, page = Model.currPage - 1}, new CustomArgs( "prev", "yada" ) )%>
It's just the idea, it's not tested.
#3 building
I finally used a common hyperlink and Url.Action, such as:
<a href='<%= Url.Action("Show", new { controller = "Browse", id = node.Id }) %>' data-nodeId='<%= node.Id %>'> <%: node.Name %> </a>
It's uglier, but you have more control over the a tag, which is sometimes useful on many Ajax sites.
HTH
#4 building
You can use it like this:
At Mvc:
@Html.TextBoxFor(x=>x.Id,new{@data_val_number="10"});
In Html:
<input type="text" name="Id" data_val_number="10"/>
#5 building
You can render with underscores ('u ') in mvc 4
Razor:
@Html.ActionLink("Vote", "#", new { id = item.FileId, }, new { @class = "votes", data_fid = item.FileId, data_jid = item.JudgeID, })
Html rendered
<a class="votes" data-fid="18587" data-jid="9" href="/Home/%23/18587">Vote</a>