I know I can add html attributes to my tag by doing something 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 I can add attributes in a similar way by using markup instead of a tag builder. Maybe something like:
var htmlAttributes = new RouteValueDictionary { { "data-foo", "bar" } };
<div @htmlAttributes.ToHtmlAttributes() ></div>
Expected output:
<div data-foo="bar"></div>
Clearly, I wouldn't be able to handle merge conflicts this way. However, I think it's worth it because the second way is so much more readable.
You can write your own extension method:
which will be used exactly how you've described:
the result is:
Edit:
If you want to use
TagBuilder
, you can alternatively write another extension which uses it internally:and the usage shown below below gives the same output html as previously: