3

When using TagBuilder one can use TagBuilder.Attributes.Add(..) or TagBuilder. MergeAttribute(..) to add attributes to the HTML element under construction:

TagBuilder formBuilder = new TagBuilder("form");
formBuilder.Attributes.Add("method", "get");
formBuilder.Attributes.Add("action", url);

TagBuilder buttonBuilder = new TagBuilder("input");
buttonBuilder.MergeAttribute("type", "submit");
buttonBuilder.MergeAttribute("value", buttonText);

But how are the two different and when should I prefer one over the other?

Peter O.
  • 32,158
  • 14
  • 82
  • 96
Henrik Stenbæk
  • 3,982
  • 5
  • 31
  • 33
  • As far as I can tell, they do the same... From MSDN (for the MergeAttribute-method): "Adds an attribute to the tag by using the specified key/value pair.". This pretty much looks the same as adding them through the Attributes-property. – Abbas Oct 24 '12 at 11:58

1 Answers1

5

By looking at the TagBuilder with dotPeek, I can see that Attributes is an SortedDictionary

From ctor:

this.Attributes = new SortedDictionary<string, string>(StringComparer.Ordinal);

Calling Add on a SotredSet ends out calling an internal function AddIfNotPresent(item)

public bool Add(T item)
{
  return this.AddIfNotPresent(item);
}

This means that Attributes.Add is the same as calling MergeAttribute without setting replaceExisting == true.

   public void MergeAttribute(string key, string value, bool replaceExisting)
    {
      ...

      if (!replaceExisting && this.Attributes.ContainsKey(key))
        return;
      this.Attributes[key] = value;
    }

So my advice will be to use MergeAttribute over Add and always specify replaceExisting for readability and to make sure not to have unexpected outcomes.

Henrik Stenbæk
  • 3,982
  • 5
  • 31
  • 33