ASP.NET MVC 3 Razor recursive function

后端 未结 2 1477
不知归路
不知归路 2020-12-04 07:02

Okay, so I want to display a list containing lists of lists of lists...

I have no way of knowing how many levels there are to display, so I figured this is where I b

相关标签:
2条回答
  • 2020-12-04 07:47

    The Razor view engine allows to write inline recursive helpers with the @helper keyword.

    @helper ShowTree(IEnumerable<Foo> foos)
    {
        <ul>
            @foreach (var foo in foos)
            {
                <li>
                    @foo.Title
                    @if (foo.Children.Any())
                    {
                        @ShowTree(foo.Children)
                    }
                </li>
            }
        </ul>
    }
    
    0 讨论(0)
  • 2020-12-04 07:49

    I think it is best to create an HTML helper for this. Something like this:

    public static string ShowSubItems(this HtmlHelper helper, MyObject _object)
    {
         StringBuilder output = new StringBuilder();
         if(_object.ListOfObjects.Count > 0)
         {
             output.Append("<ul>");
    
             foreach(MyObject subItem in _object.listOfObjects)
             {
                 output.Append("<li>");
                 output.Append(_object.Title);
                 output.Append(html.ShowSubItems(subItem.listOfObjects);
                 output.Append("</li>")
             }
             output.Append("</ul>");
         }
         return output.ToString();
    }
    

    Then call it like this:

    @foreach(MyObject item in @Model.ListOfObjects){
        <div> @item.Title </div>
        @html.ShowSubItems(item)
    }
    
    0 讨论(0)
提交回复
热议问题