Passing an object to HTML attributes

后端 未结 3 1120
误落风尘
误落风尘 2020-12-13 04:06

How to pass an object to HTML attributes? For example I have the following code:

var attrs = new { id = \"myid\", style = \"color: Red;\" };
<
相关标签:
3条回答
  • 2020-12-13 04:22

    You do not need to convert to a string. The last paramater for HTML Helpers is an Object. You just give it the object like you have written above:

    For exmample

    @Html.TextBoxFor(x => x.Foo, new { size = 10, maxlength = 10 }) 
    @Html.TextAreaFor(x => x.Notes, new { @class = "additionalInfo" })
    @Html.TextBoxFor(x=>x.Registration.Address.Postcode, new {type="number", @class="postcode numeric", size=5, maxlength=5})
    

    on a side note you probably should not be setting styles directy inline with your HTML and use a CSS class/selector instead with a seperate style sheet. Also the ID of each DOM element should automatically be set when you use MVC HTML helpers

    0 讨论(0)
  • 2020-12-13 04:35

    This functionality is, surprisingly enough, provided by the RouteValueDictionary class:

    IDictionary<string, object> htmlAttributes = new RouteValueDictionary(attrs);
    

    You can then use this dictionary in conjunction with a TagBuilder, which you will probably be using anyway:

    var tagBuilder = new TagBuilder("input");
    tagBuilder.MergeAttributes(htmlAttributes);
    tagBuilder.ToString(TagRenderMode.Normal);
    

    You can see this done in the ASP.NET MVC source code itself; one of the simpler examples is in TextAreaExtensions.cs.

    EDIT:

    In order to properly convert "data_attr" to "data-attr", use the AnonymousObjectToHtmlAttributes static method.

    IDictionary<string, object> htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(attrs);
    
    0 讨论(0)
  • 2020-12-13 04:38

    Here's how to do this conversion :

    var htmlAttributes = new { id="myid", @class="myclass" };
    
    string string_htmlAttributes = "";
    foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(htmlAttributes))
    {
      string_htmlAttributes += string.Format("{0}=\"{1}\" ", property.Name.Replace('_', '-'), property.GetValue(htmlAttributes));
    }
    

    PropertyDescriptor belong to the class System.ComponentModel

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