I am trying to make a HtmlHelper and I need to allow users to add their own custom attributes to the html tag.
I tried to do this using the TagBuilder class, but it seems that instead of merging the attributes, it just replaces them.
This is what I did in C#:
public static MvcHtmlString List(HtmlHelper helper, object htmlAttributes)
{
var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
var tag = new TagBuilder("div");
tag.AddCssClass("myClass");
tag.MergeAttributes(attributes, false);
// tag class property has value "myClass", not "myClass testClass"
return new MvcHtmlString("<div>");
}
This is my view:
@Html.List(new { @class = "testClass" })
What am I doing wrong?
The
TagBuilder.MergeAttributesmethod doesn't work how you expect it to. This is the exact code of this method:As you can see it only adds new attributes to the collection (if
replaceExistingis set to true it also replaces the ones already in the collection). It doesn't perform and attributes values merging logic. If you want to merge values you need to do it by yourself: