Passing an object to HTML attributes

后端 未结 3 1130
误落风尘
误落风尘 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: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

提交回复
热议问题