使用tagbuilder构建多个无序列表

时间:2013-05-20 18:35:30

标签: c# asp.net-mvc tagbuilder

我正在尝试使用tagbuilder构建两个unordered lists

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

1 个答案:

答案 0 :(得分:2)

如果我理解您的问题,您应该使用单独的StringBuilder来保存生成的HTML输出。在继续生成第二个UL之前,这将为您提供存储第一个UL结果的位置。

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