Recursion in an ASP.NET MVC view

后端 未结 4 1034
后悔当初
后悔当初 2020-12-01 03:58

I have a nested data object for a set of items within categories. Each category can contain sub categories and there is no set limit to the depth of sub categories. (A file

4条回答
  •  独厮守ぢ
    2020-12-01 04:20

    Create your own HtmlHelper extension method like so:

    namespace System.Web.Mvc
    {
        public static class HtmlHelperExtensions
        {
            public static string CategoryTree(this HtmlHelper html, IEnumerable categories)
            {
                string htmlOutput = string.Empty;
    
                if (categories.Count() > 0)
                {
                    htmlOutput += "
      "; foreach (Category category in Categories) { htmlOutput += "
    • "; htmlOutput += category.Name; htmlOutput += html.CategoryTree(category.Categories); htmlOutput += "
    • "; } htmlOutput += "
    "; } return htmlOutput; } } }

    Funny you should ask because I actually created one of these just yesterday.

提交回复
热议问题