c# - RouteValueDictionary to HtmlAttributes -


i know can add html attributes tag doing like:

var htmlattributes = new routevaluedictionary { { "data-foo", "bar" } }; var tag = new tagbuilder("div"); tag.mergeattributes(htmlattributes ); @tag 

output:

<div data-foo="bar"></div> 

i wonder if can add attributes in similar way using markup instead of tag builder. maybe like:

var htmlattributes = new routevaluedictionary { { "data-foo", "bar" } }; <div @htmlattributes.tohtmlattributes() ></div> 

expected output:

<div data-foo="bar"></div> 

clearly, wouldn't able handle merge conflicts way. however, think it's worth because second way more readable.

you can write own extension method:

namespace somenamespace {     public static class routevaluedictionaryextensions     {         public static ihtmlstring tohtmlattributes(this routevaluedictionary dictionary)         {             var sb = new stringbuilder();             foreach (var kvp in dictionary)             {                 sb.append(string.format("{0}=\"{1}\" ", kvp.key, kvp.value));             }             return new htmlstring(sb.tostring());         }     } } 

which used how you've described:

@using somenamespace     @{     var htmlattributes = new routevaluedictionary         {             {"data-foo", "bar"},             {"data-bar", "foo"}         }; }  <div @htmlattributes.tohtmlattributes()> </div> 

the result is:

<div data-foo="bar" data-bar="foo" > </div> 

edit:

if want use tagbuilder, can alternatively write extension uses internally:

public static ihtmlstring tag(this htmlhelper helper,                                routevaluedictionary dictionary,                                string tagname) {     var tag = new tagbuilder(tagname);     tag.mergeattributes(dictionary);     return new htmlstring(tag.tostring()); } 

and usage shown below below gives same output html previously:

@html.tag(htmlattributes, "div") 

Comments

Popular posts from this blog

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

html - How to style widget with post count different than without post count -

url rewriting - How to redirect a http POST with urlrewritefilter -