Search code examples
asp.net-mvcrazortagbuilder

Nested TagBuilder -as TagBuilderTree-


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?


Solution

  • 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();
    }