我试图使用HTML5的数据属性在我的ASP。NET MVC 1项目。(我是c#和ASP。NET MVC新手。)
<%= Html.ActionLink("« Previous", "Search",
new { keyword = Model.Keyword, page = Model.currPage - 1},
new { @class = "prev", data-details = "Some Details" })%>
上面htmlAttributes中的"data-details"给出以下错误:
CS0746: Invalid anonymous type member declarator. Anonymous type members
must be declared with a member assignment, simple name or member access.
当我使用data_details时,它可以工作,但我猜它需要按照规范以“data-”开始。
我的问题:
是否有任何方法让这个工作和使用HTML5数据属性与Html。ActionLink或类似的Html助手?
是否有其他可选的机制将自定义数据附加到元素?这些数据稍后将由JS处理。
更新:MVC 3和更新的版本对此有内置的支持。下面是JohnnyO获得高度好评的回答,请参阅推荐的解决方案。
我不认为有什么立竿见影的帮助来实现这一目标,但我确实有两个想法供你尝试:
// 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" ) )%>
只是想法,还没有测试过。
更新:MVC 3和更新的版本对此有内置的支持。下面是JohnnyO获得高度好评的回答,请参阅推荐的解决方案。
我不认为有什么立竿见影的帮助来实现这一目标,但我确实有两个想法供你尝试:
// 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" ) )%>
只是想法,还没有测试过。
我不喜欢使用纯“a”标签,输入太多。所以我提出了解决方案。
从这个角度来看
<%: Html.ActionLink(node.Name, "Show", "Browse",
Dic.Route("id", node.Id), Dic.New("data-nodeId", node.Id)) %>
Dic类的实现
public static class Dic
{
public static Dictionary<string, object> New(params object[] attrs)
{
var res = new Dictionary<string, object>();
for (var i = 0; i < attrs.Length; i = i + 2)
res.Add(attrs[i].ToString(), attrs[i + 1]);
return res;
}
public static RouteValueDictionary Route(params object[] attrs)
{
return new RouteValueDictionary(Dic.New(attrs));
}
}