Nested TagBuilder -as TagBuilderTree-

Nuri YILMAZ picture Nuri YILMAZ · Feb 10, 2011 · Viewed 23.7k times · Source

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?

Answer

SLaks picture SLaks · Feb 10, 2011

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)

TagBuilder select = new TagBuilder("select");  

foreach (var language in languages) // never ye mind about languages
{
    TagBuilder option = new TagBuilder("option");
    option.MergeAttribute("value", language.ID.ToString());

    if (language.IsCurrent)
    {
        option.MergeAttribute("selected", "selected");
    }

    option.InnerHtml = language.Description;
    // And now, the money-code:
    select.InnerHtml += option.ToString();
}