如何在ASP.NET MVC中的HTML-5 data- \*属性中使用破折号

asp.net-mvc HTML

西里神奇

2020-03-24

我正在尝试在ASP.NET MVC 1项目中使用HTML5数据属性(我是C#和ASP.NET MVC新手。)

 <%= Html.ActionLink("« Previous", "Search",
     new { keyword = Model.Keyword, page = Model.currPage - 1},
     new { @class = "prev", data-details = "Some Details"   })%>

上面的htmlAttributes中的“数据细节”给出以下错误:

 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处理此数据。

第3244篇《如何在ASP.NET MVC中的HTML-5 data- \*属性中使用破折号》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

6个回答
村村阿飞 2020.03.24

我不喜欢使用纯粹的“ 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));
    }
}
神无 2020.03.24

您可以像这样使用它:

在Mvc中:

@Html.TextBoxFor(x=>x.Id,new{@data_val_number="10"});

在HTML中:

<input type="text" name="Id" data_val_number="10"/>
神无番长 2020.03.24

它比上面建议的一切还要容易。MVC中包含短划线(-)的数据属性通过使用下划线(_)来满足。

<%= Html.ActionLink("« Previous", "Search",
 new { keyword = Model.Keyword, page = Model.currPage - 1},
 new { @class = "prev", data_details = "Some Details"   })%>

我看到JohnnyO已经提到了这一点。

乐米亚 2020.03.24

您可以使用新的Html帮助程序扩展功能来实现此功能,然后将其与现有的ActionLinks相似地使用。

public static MvcHtmlString ActionLinkHtml5Data(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes, object htmlDataAttributes)
{
    if (string.IsNullOrEmpty(linkText))
    {
        throw new ArgumentException(string.Empty, "linkText");
    }

    var html = new RouteValueDictionary(htmlAttributes);
    var data = new RouteValueDictionary(htmlDataAttributes);

    foreach (var attributes in data)
    {
        html.Add(string.Format("data-{0}", attributes.Key), attributes.Value);
    }

    return MvcHtmlString.Create(HtmlHelper.GenerateLink(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection, linkText, null, actionName, controllerName, new RouteValueDictionary(routeValues), html));
}

你这样称呼它...

<%: Html.ActionLinkHtml5Data("link display", "Action", "Controller", new { id = Model.Id }, new { @class="link" }, new { extra = "some extra info" })  %>

简单:-)

编辑

在这里多写一点

小卤蛋 2020.03.24

在mvc 4中可以用Underscore(“ _”)渲染

剃刀:

@Html.ActionLink("Vote", "#", new { id = item.FileId, }, new { @class = "votes", data_fid = item.FileId, data_jid = item.JudgeID, })

呈现的HTML

<a class="votes" data-fid="18587" data-jid="9" href="/Home/%23/18587">Vote</a>
TomMandy 2020.03.24

更新: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" ) )%>

只是想法,还没有测试。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android