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
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>
}
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)
}