TagBuilder
is a class that specially designed for creating html tags and their content. You are right saying that result will be anyway a string and of course you still can use StringBuilder
and the result will be the same, but you can do things easier with TagBuilder
. Lets say you need to generate a tag:
<a href='http://www.stackoverflow.com' class='coolLink'/>
Using StringBuilder
you need to write something like this:
var sb = new StringBuilder();
sb.Append("<a href='");
sb.Append(link);
sb.Append("' class = '");
sb.Append(ccsClass);
sb.Append("'/>");
sb.ToString();
It is not very cool, isn’t it?
And compare how you can build it using TagBuilder
;
var tb = new TagBuilder("a");
tb.MergeAttribute("href",link);
tb.AddCssClass(cssClass);
tb.ToString(TagRenderMode.SelfClosing);
Isn't that better?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…