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

C# 如何在ASP.NET MVC中向html元素添加数据属性?,c#,asp.net-mvc,C#,Asp.net Mvc,我了解到,添加数据属性是向html元素添加自定义信息的好方法。所以我试着这样做: <%= Html.TextBox ("textBox", "Value", new { data-myid = m.ID })%> 但它最终会导致语法错误。如何定义自定义数据属性 编辑: 我认为我可以通过以下方式实现此效果: <%= Html.TextBox ("textBox", "Value", new Dictionary<string, object> {{ "data-

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

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

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

编辑:

我认为我可以通过以下方式实现此效果:

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


但那看起来不…嗯…干净!有更好的方法吗?

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

我找不到任何方法获取匿名类型声明以接受
数据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);
            }
        }

    }
}
然而,这让您不得不在任何其他想要接受数据属性的方法上创建重载,这是一个难题。你可以通过将逻辑转移到

public static IDictionary<string,object> MergeDataAttributes(
    this HtmlHelper htmlHelper,
    object htmlAttributes,
    object dataAttributes)
公共静态IDictionary合并数据属性(
这个HtmlHelper HtmlHelper,
对象属性,
对象数据(属性)
并称之为

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

使用下划线而不是破折号

new{data\u myid=m.ID}

这个在MVC3中肯定有效(没有检查其他版本)。呈现HTML时,下划线将转换为破折号

编辑


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

请参阅此问题“使用asp.net MVC连接html属性”注意:较新的正确答案是,如果您不喜欢滚动,请在本页下方更远的位置;)我将此标记为答案,因为它更简洁。
<%= Html.TextBox ("textBox", "Value",
        Html.MergeDataAttributes( new { title = "Some ordinary attribute" }, new { myid = m.ID } ) ) %>