本文介绍了如何在 ASP.NET MVC 中的 HTML-5 data-* 属性中使用破折号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在我的 ASP 中使用 HTML5 数据属性.NET MVC 1 项目.(我是 C# 和 ASP.NET MVC 新手.)
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" })%>
上述htmlAttributes中的data-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.
当我使用 data_details 时它有效,但我想它需要按照规范以data-"开头.
It works when I use data_details, but I guess it need to be starting with "data-" as per the spec.
我的问题:
- 有没有什么办法可以让这个工作并使用 HTML5 数据属性与 Html.ActionLink 或类似的 Html 助手?
- 是否有其他替代机制可以将自定义数据附加到元素?此数据稍后由 JS 处理.
推荐答案
更新:MVC 3 和更新版本对此有内置支持.有关推荐的解决方案,请参阅下面 JohnnyO 高度赞成的答案.
我不认为有任何直接的帮助可以实现这一目标,但我确实有两个想法供您尝试:
I do not think there are any immediate helpers for achieving this, but I do 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" ) )%>
只是想法,还没有测试过.
Just ideas, haven't tested it.
这篇关于如何在 ASP.NET MVC 中的 HTML-5 data-* 属性中使用破折号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!