如何在ASP.NET MVC中的HTML-5 data- *属性中使用破折号 [英] How to use dashes in HTML-5 data-* attributes in ASP.NET MVC
问题描述
我正在尝试在我的ASP中使用 HTML5数据属性。 NET MVC 1项目。 (我是C#和ASP.NET MVC新手。)
<%= Html.ActionLink(«Previous, Search,
new {keyword = Model.Keyword,page = Model.currPage - 1},
new {@class =prev,data-details =一些细节})%> ;
上述htmlAttributes中的data-details给出了以下错误:
CS0746:无效的匿名类型成员声明符。匿名类型成员
必须用成员分配,简单名称或成员访问来声明。
它在我使用data_details的时候很有用,但我想它应该以data-开始每个规格。
我的问题:
- 有什么方法可以获得这与Html.ActionLink或类似的Html助手一起使用和使用HTML5数据属性?
- 是否有其他替代机制将自定义数据附加到元素?这些数据将在稍后由JS处理。 更新:MVC 3新版本内置了对此的支持。
我不认为有任何直接的帮手来实现这个目标,但我对你有两个想法尝试:
// 1:传递字典而不是匿名对象
<%= Html.ActionLink(返回,搜索,
new {keyword = Model.Keyword,page = Model.currPage - 1},
new Dictionary< string,Object> {{class,prev}, {data-details,yada}}}%>
//传递用描述符属性装饰的自定义类型
public class CustomArgs
{
public CustomArgs(string className,string dataDetails){...}
[DisplayName(class)]
public string Class {get;组; }
[DisplayName(data-details)]
public string DataDetails {get;组; }
}
<%= Html.ActionLink(back,Search,
new {keyword = Model.Keyword,page = Model.currPage - 1} ,
新CustomArgs(prev,yada))%>
只是想法,尚未测试过。
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.
解决方案Update: MVC 3 and newer versions have built-in support for this. See JohnnyO's highly upvoted answer below for recommended solutions.
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- *属性中使用破折号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!