[ACCEPTED]-ASP.NET MVC 3 Razor recursive function-razor

Accepted answer
Score: 217

The Razor view engine allows to write inline 1 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>
}
Score: 13

I think it is best to create an HTML helper 2 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 1 it like this:

@foreach(MyObject item in @Model.ListOfObjects){
    <div> @item.Title </div>
    @html.ShowSubItems(item)
}
Score: 3

In .Net core Instead of helper tag we have 3 to use @functions. This below code might 2 useful to some people. Here "IssuerData" is 1 my custom object

@{
      ShowTreeData(Model.HierarchyList);
}

    @functions{

  public static void ShowTreeData(IList<IssuerData> issuers)
      {
       <ul>
      @foreach (var i in issuers)
           {
           <li>
            @i.IssuerName
             @if (i.Children.Any())
               {
                 ShowTreeData(i.Children);
               }
            </li>
          }
       </ul>
       }
   }

More Related questions