How can I turn an anonymous object into key / value pairs or HTML attributes?

In my MVC application, I have a helper class designed to display a group of related buttons. I am trying to pass HTML attributes as an anonymous object:

new { @class="myClass1 myClass2" } 

The helper passes the HTML as an MvcHtmlString , which I am currently creating as follows:

  foreach (var b in _buttons) { sb.AppendFormat("<button type='submit' name='{0}' {1}>{2}</button>", b.Value, b.HtmlAttributes, b.Text); } 

My problem is that the above code creates invalid HTML:

 <button type='submit' name='Foo' { class = myClass1 myClass2 }>Bar</button> 

Unfortunately, since it is passed to the helper as an object , I have no information about the type you are working with. I could have a ToString object and parse the result, but that seems pretty dumb. How can I programmatically convert an anonymous object to key="value" style HTML attributes? Is there an existing utility for this?

+4
source share
2 answers

You should use the TagBuilder class, which creates HTML tags for you.

Then you can write

 builder.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(HtmlAttributes)); 
+14
source

As it turned out, the HtmlHelper class has a static method:

 HtmlHelper.AnonymousObjectToHtmlAttributes(b.HtmlAttributes) 

This solved my problem:

  foreach (var b in _buttons) { var dict = HtmlHelper.AnonymousObjectToHtmlAttributes(b.HtmlAttributes); var attr = dict.Keys.Zip( dict.Values, (k, v) => string.Format("{0}='{1}'", k, v)); sb.AppendFormat("<button type='submit' name='{0}' {1}>{2}</button>", b.Value, string.Join(" ", attr), b.Text); } 

I also tried it with TagBuilder and got about the same amount of code.


Edit: As Slax noted, completing this task is a potential XSS vulnerability. In my particular use case there was no risk, but TagBuilder seems to be the best practice.

+3
source

Source: https://habr.com/ru/post/1399054/


All Articles