ASP.NET MVC 3 Recursive Razor Function

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

I have no way of knowing how many levels to display, so I decided that this is where I exit the old recursive procedure.

I am having problems with how to do this, though.

This is what I have so far (apparently simplified):

@foreach(MyObject item in @Model.ListOfObjects){ <div> @item.Title </div> //Call recursive function? } 

Now each of these objects also has a List <MyObject>. I want to display each level below this div, for example, indented tabs per level.

I thought the Razor function would be here, but I need help in building it. Here is my thinking:

 @functions{ public static void ShowSubItems(MyObject _object){ if(_object.ListOfObjects.Count>0){ foreach(MyObject subItem in _object.listOfObjects){ // Show subItem in HTML ShowSubItems(subItem); } } } } 

But, as you can see, I clearly need help :)

+64
c # asp.net-mvc asp.net-mvc-3 razor
Jun 21 '11 at 9:10
source share
2 answers

Razor's view engine allows you to write built-in recursive helpers with the @helper .

 @helper ShowTree(IEnumerable<Foo> foos) { <ul> @foreach (var foo in foos) { <li> @foo.Title @if (foo.Children.Any()) { @ShowTree(foo.Children) } </li> } </ul> } 
+175
Jun 21 2018-11-11T00:
source share

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

 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 name it like this:

 @foreach(MyObject item in @Model.ListOfObjects){ <div> @item.Title </div> @html.ShowSubItems(item) } 
+12
Jun 21 '11 at 9:26 a.m.
source share



All Articles