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

前端 未结 3 889
南方客
南方客 2020-12-29 02:38

I learned few minutes ago that adding data attributes is a nice way to add custom information to html elements. So I tried to do like this:

<%= Html.TextB         


        
相关标签:
3条回答
  • 2020-12-29 03:24

    I can't see any way to get an anonymous type declaration to accept data-myid, since that's not a valid property name in C#. One option would be to create a new overload that takes an extra dataAttributes parameter, and prepends data- to the names for you...

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

    Then you can add a data-myid attribute with

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

    However, that leaves you to create that overload on any other methods that you want to accept data attributes, which is a pain. You could get around that by moving the logic to a

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

    and call it as

    <%= Html.TextBox ("textBox", "Value",
            Html.MergeDataAttributes( new { title = "Some ordinary attribute" }, new { myid = m.ID } ) ) %>
    
    0 讨论(0)
  • 2020-12-29 03:37

    Use an underscore instead of a dash.

    new { data_myid = m.ID }

    This definitely works in MVC3 (haven't checked other versions). The underscore will be converted to a dash when the HTML is rendered.

    EDIT

    This works in the latest versions of MVC too.

    0 讨论(0)
  • 2020-12-29 03:40

    I think you will have to create your own helper to do this for you. I cannot find a way to do this directly in the view.

    0 讨论(0)
提交回复
热议问题