TagBuilder.MergeAttributes does not work as expected

Catalin picture Catalin · Sep 28, 2012 · Viewed 9.7k times · Source

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?

Answer

user755404 picture user755404 · Nov 8, 2012

The MergeAttributes overrides the attributes already on the tag, AddCssClass appends the name in the class value.

So just switch it around and it will work;

    tag.MergeAttributes(attributes, false);
    tag.AddCssClass("myClass");

AddCssClass will append to the class name(s) merged above it.