TagBuilder is a nice implementation for build HTML elements. But -some- HTML elements can have another elements (I called like children). I could not find any class from Mvc classes.
Question; Should I implement few classes (TagBuilderTree, and TagBuilderNode) which support nested tags or did I miss something?
You can build the child elements in separate TagBuilders and put their generated HTML in the parent TagBuilder.
Here's an example: A
<select>
with some<option>
s (example de-fatted for terseness)The problem that I have with TagBuilder to create tags is that it looks very un-maintainable. On the other hand, StringBuilder's AppendFormat not only makes the code maintainable, but also run with good efficiency.
I've made a slight improvement to MattSlay 's #1 method. I used only one call to StringBuilder's AppendFormat method and used the C# string literal to define the format. As a result the format ends up looking exactly like the desired result and runs with efficiency.
Hope this helps!
OK, I decided to do a little test in my own code base.
I compared these two methods to create the same exact final HTML:
Manually generating the html using a StringBuilder:
Using multiple TagBuilders and merging the content:
To me, #1 is easier to read and much more concise, but I can appreciat the structure of #2 also.