【问题标题】:Is there a way to create an ActionLink with HTML 5 Data- attributes?有没有办法使用 HTML 5 Data- 属性创建 ActionLink?
【发布时间】:2010-02-26 02:18:43
【问题描述】:

HTML5 允许使用以短语“data-”为前缀的自定义属性,无需使用自定义 DTD (more info) 即可通过验证。在 Asp.Net MVC 中,有没有办法指定带有 data- 属性的 ActionLink?

向 ActionLink 添加属性的典型方法是传入一个匿名对象,每个对象都有一个自定义属性:

new { customattribute="value" }

我想做的是:

new { data-customattribute="value" }

但这不起作用,因为连字符在属性名称中无效。有没有办法绕过这个限制?还是我只需要在使用 ActionLinks 和使用 data- 属性之间做出选择?

【问题讨论】:

    标签: asp.net-mvc html


    【解决方案1】:

    或者你可以使用

    new { data_customattribute="value" }

    编译器足够聪明,知道你的意思

    【讨论】:

    • 是的,要在 mvc3 之前的版本中实现相同的解决方案,您应该使用 @çağdaş 解决方案
    【解决方案2】:

    是的,ActionLink 方法有一个重载,它采用 IDictionary<string,object> 而不是匿名对象。

    <%=Html.ActionLink("text", "Index", "Home", null /*routeValues*/, 
        new Dictionary<string, object> { 
           { "data-customattribute", "value" }, 
           { "data-another", "another-value" } 
        })%>
    

    输出:

    <a data-another="another-value" data-customattribute="value" href="/">text</a>
    

    【讨论】:

    • 完美。未来读者请注意:如果您对 HTML 属性使用 IDictionary,则还必须对 routeValues 参数使用 RouteDictionary(您可以使用与上述 HTML 属性相同的语法)。
    猜你喜欢
    • 2011-09-22
    • 2011-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-25
    • 2021-12-08
    • 1970-01-01
    • 2011-05-05
    相关资源
    最近更新 更多