【问题标题】:How to add data attributes to html element in ASP.NET MVC?如何在 ASP.NET MVC 中向 html 元素添加数据属性?
【发布时间】:2018-04-14 02:14:59
【问题描述】:

我了解到few minutes ago 添加数据属性是向 html 元素添加自定义信息的好方法。所以我试着这样做:

<%= Html.TextBox ("textBox", "Value", new { data-myid = m.ID })%>

但它最终会导致语法错误。如何定义自定义数据属性?

编辑:

我发现我可以使用:

<%= Html.TextBox ("textBox", "Value", new Dictionary<string, object> {{ "data-myid", m.ID }})%>

但这看起来并不...嗯...干净!有没有更好的方法来做到这一点?

【问题讨论】:

标签: c# asp.net-mvc


【解决方案1】:

使用下划线代替破折号。

new { data_myid = m.ID }

绝对适用于 MVC3(尚未检查其他版本)。渲染 HTML 时,下划线将转换为破折号。

编辑

这也适用于最新版本的 MVC。

【讨论】:

  • 我将此标记为答案,因为它更简洁。
【解决方案2】:

我看不到任何方法可以让匿名类型声明接受data-myid,因为这不是 C# 中的有效属性名称。一种选择是创建一个新的重载,该重载采用额外的dataAttributes 参数,并为您的名称添加data-...

using System.ComponentModel;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Routing;

static class TextBoxExtensions
{
    public static string TextBox(this HtmlHelper htmlHelper, string name, object value, object htmlAttributes, object dataAttributes)
    {
        RouteValueDictionary attributes = new RouteValueDictionary(htmlAttributes);
        attributes.AddDataAttributes(dataAttributes);

        return htmlHelper.TextBox(
            name, 
            value, 
            ((IDictionary<string, object>)attributes);
    }

    private static void AddDataAttributes(this RouteValueDictionary dictionary, object values)
    {
        if (values != null)
        {
            foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(values))
            {
                object obj2 = descriptor.GetValue(values);
                dictionary.Add("data-" + descriptor.Name, obj2);
            }
        }

    }
}

然后你可以添加一个data-myid属性

<%= Html.TextBox ("textBox", "Value",
        new { title = "Some ordinary attribute" },
        new { myid = m.ID }) %>

但是,这会让您在要接受数据属性的任何其他方法上创建该重载,这很痛苦。您可以通过将逻辑移至

public static IDictionary<string,object> MergeDataAttributes(
    this HtmlHelper htmlHelper,
    object htmlAttributes,
    object dataAttributes)

并将其称为

<%= Html.TextBox ("textBox", "Value",
        Html.MergeDataAttributes( new { title = "Some ordinary attribute" }, new { myid = m.ID } ) ) %>

【讨论】:

    【解决方案3】:

    我认为您必须创建自己的助手来为您执行此操作。我找不到直接在视图中执行此操作的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-26
      • 1970-01-01
      • 2011-02-08
      • 2011-02-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多