How to get values out of object HtmlAttributes

前端 未结 3 810
一生所求
一生所求 2021-02-02 10:49

In asp.net mvc I always see the built in html helpers they always have object htmlAttirbutes.

Then I usually do new {@id = \"test\", @class=\"myClass\"}.

How do

3条回答
  •  無奈伤痛
    2021-02-02 11:32

    I usually do something like this:

       public static string Label(this HtmlHelper htmlHelper, string forName, string labelText, object htmlAttributes)
        {
            return Label(htmlHelper, forName, labelText, new RouteValueDictionary(htmlAttributes));
        }
    
        public static string Label(this HtmlHelper htmlHelper, string forName, string labelText,
                                   IDictionary htmlAttributes)
        {
            // Get the id
            if (htmlAttributes.ContainsKey("Id"))
            {
                string id = htmlAttributes["Id"] as string;
            }
    
            TagBuilder tagBuilder = new TagBuilder("label");
            tagBuilder.MergeAttributes(htmlAttributes);
            tagBuilder.MergeAttribute("for", forName, true);
            tagBuilder.SetInnerText(labelText);
            return tagBuilder.ToString();
        }
    

    I suggest you to download the ASP.NET MVC source from the codeplex and take a look at the built in html helpers.

提交回复
热议问题