D
D
DSergeev2014-10-17 13:19:07
ASP.NET
DSergeev, 2014-10-17 13:19:07

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

1 answer(s)
D
DSergeev, 2014-10-17
@DSergeev

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 "";
        }
    }

ps Even on this toaster, there are only views, and 0 answers. Even damn it, there is no one to consult with, everyone is silent!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question