I find the TagBuilder written in C# little poor without the ability to "host" inside it sub tags (as objects not as strings).
So I wrote a simple class that inherits TagBuilder and allow to save sub tags. I can navigate inside it and add things to it while I move across the application. And when I call the Top Tag Object .ToString, it will render the entire html
public class MultiLevelHtmlTag : TagBuilder
{
public MultiLevelHtmlTag(string tagName) : base(tagName) { }
public List<MultiLevelHtmlTag> InnerTags = new List<MultiLevelHtmlTag>();
public override string ToString()
{
if (InnerTags.Count > 0)
{
foreach (MultiLevelHtmlTag tag in InnerTags)
{
this.InnerHtml += tag.ToString();
}
}
return base.ToString();
}
}
this is how I use it:
MultiLevelHtmlTag top = new MultiLevelHtmlTag("div");
top.InnerTags.Add(new MultiLevelHtmlTag("span"));
log.Debug(top.ToString());
output:
<div><span></span></div>
What do you think about it? is that a goot pattern?
ToString()
method has some major problems. See what happens if you call it multiple times. It should only return a string representation of the object. It shouldn't be modifying it. \$\endgroup\$