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?
By looking at the
TagBuilder
with dotPeek, I can see that Attributes is an SortedDictionaryFrom ctor:
Calling Add on a SotredSet ends out calling an internal function AddIfNotPresent(item)
This means that
Attributes.Add
is the same as calling MergeAttribute without settingreplaceExisting == true
.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.