如何在ASP.NET MVC中向html元素添加数据属性?

Hem*_*ant 31 c# asp.net-mvc

几分钟前才知道,添加数据属性是向html元素添加自定义信息的好方法.所以我试着这样做:

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

但最终会出现语法错误.如何定义自定义数据属性?

编辑:

我看到我可以使用以下方法实现此效果:

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

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

Lee*_*unn 107

使用下划线而不是破折号.

new { data_myid = m.ID }

肯定适用于MVC3(尚未检查其他版本).在呈现HTML时,下划线将转换为破折号.

编辑

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

  • 也适用于MCC 4. (6认同)
  • 这绝对应该标明答案:) (3认同)

ste*_*son 5

我看不到任何方式来获取匿名类型声明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);
            }
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

但是,这会让您在要接受数据属性的任何其他方法上创建该重载,这很痛苦.你可以通过将逻辑移动到a来解决这个问题

public static IDictionary<string,object> MergeDataAttributes(
    this HtmlHelper htmlHelper,
    object htmlAttributes,
    object dataAttributes)
Run Code Online (Sandbox Code Playgroud)

并称之为

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