Search code examples
c#asp.net-mvctagbuilder

Build mulitple unordered lists using tagbuilder


I am trying to build two unordered lists using a tagbuilder.

  public static MvcHtmlString GenerateMultipleUL<T>(this HtmlHelper html, IGridable<T> model)
        where T : class
            { 
            int itemsCount = model.RowModels.Count();
            TagBuilder ulTag = new TagBuilder("ul");                 
            foreach(var indexedItem in model.RowModels.Select((p, i)=> new {item = p, Index = i}))
                {
                    if (itemsCount / 2 == indexedItem.Index)
                    {  //create a new Un ordered List
ulTag = new TagBuilder("ul"); // This resets the old values with new ones but i want to close the old UL and create a new one.
                    }
                    TagBuilder liTag = new TagBuilder("li");
                        ..........
                    ulTag.InnerHtml += liTag;
                 }
            return new MvcHtmlString(ulTag.ToString());
            }

Solution

  • If I am understanding your question, you should be using a separate StringBuilder to hold the generated HTML for output. This will give you a place to store the results of your first UL before continuing with generating the second.

    StringBuilder output = new StringBuilder();
    TagBuilder ulTag = new TagBuilder("ul");
    foreach (var item in model)
    {
        if (testCondition(item))
        {
            output.Append(ulTag.ToString());
            ulTag = new TagBuilder("ul");
        }
        ...
    }
    output.Append(ulTag.ToString();
    return output.ToString();