繁体   English   中英

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

[英]How to add data attributes to html element in ASP.NET MVC?

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

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

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

编辑:

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

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

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

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

new { data_myid = m.ID }

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

编辑

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

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

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

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 } ) ) %>

我认为你必须创建自己的助手来为你做这件事。 我无法在视图中找到直接执行此操作的方法。

<%= Html.TextBox ("myTextBox", "", 
         new { @class="redText", title="Enter red text here"})%>

结果是:

<input type="text" id="myTextBox" class="redText" title="Enter red text here" />

我不确定你的问题是什么。 可能与您的匿名类型的属性名称中的“ - ”有关。


是的,编译器不喜欢你的属性名称。 从注释中,为了添加html5数据属性,您必须使用字典或创建另一个简化字典构造的扩展。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM