Answer the question
In order to leave comments, you need to log in
Why are nested categories not displayed (tree building ul li)?
I create a helper to build a ul li tree and something is wrong with the recursive function, only top-level categories are displayed. What's wrong? maybe there is an easier way to do this?
The data in the database is stored like this:
Id ParentId Name
1 null 1.0
2 1 1.1
3 1 1.2
4 null 2.0
The helper itself
namespace MyProject.Helpers
{
public static class TreeView
{
private static IEnumerable<Category> category;
public static MvcHtmlString DisplayTree(this HtmlHelper html, IEnumerable<Category> collection)
{
category = collection;
return NewMethod(null);
}
private static MvcHtmlString NewMethod(int? parentId)
{
TagBuilder ul = new TagBuilder("ul");
if (category.Any(x => x.ParentCategoryId == parentId))
{
foreach (var item in category.Where(x => x.ParentCategoryId == parentId))
{
TagBuilder li = new TagBuilder("li");
li.SetInnerText(item.Name);
ul.InnerHtml += li.ToString();
NewMethod(item.Id);
}
}
return new MvcHtmlString(ul.ToString());
}
}
}
Answer the question
In order to leave comments, you need to log in
Problem solved.
Working code
public static class TreeView
{
private static IEnumerable<Category> category;
public static MvcHtmlString DisplayTree(this HtmlHelper html, IEnumerable<Category> collection)
{
category = collection;
return new MvcHtmlString(NewMethod(null));
}
private static string NewMethod(int? parentId)
{
TagBuilder ul = new TagBuilder("ul");
if (category.Any(x => x.ParentCategoryId == parentId))
{
foreach (var item in category.Where(x => x.ParentCategoryId == parentId))
{
TagBuilder li = new TagBuilder("li");
li.SetInnerText(item.Name);
ul.InnerHtml += li.ToString();
ul.InnerHtml += NewMethod(item.Id);
}
return ul.ToString();
}
return "";
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question