How to render singly Linked list in MVC View page

You could create an extension method that uses recursion to build <ul> and <li> elements to show the hierarchy of folders

public static class FolderTreeExtensions
{
  public static MvcHtmlString FolderTree(this HtmlHelper helper, TreeViewFolder folder)
  {
    return MvcHtmlString.Create(TreeLeaf(folder));
  }

  // Recursive function
  private static string TreeLeaf(TreeViewFolder folder)
  {
    StringBuilder html = new StringBuilder();
    TagBuilder div = new TagBuilder("div");
    div.InnerHtml = folder.FolderName;
    html.Append(div.ToString());
    if (folder.MyTreeList != null)
    {
      foreach (TreeViewFolder subFolder in folder.MyTreeList)
      {
        html.Append(TreeLeaf(subFolder));
      }
    }
    TagBuilder item = new TagBuilder("li");
    item.InnerHtml = html.ToString();
    TagBuilder container = new TagBuilder("ul");
    container.InnerHtml = item.ToString();       
    return container.ToString();
  }
}

Then in your controller, initialize and populate and instance of TreeViewFolder, and in the view

@model TreeViewFolder
....
@Html.FolderTree(Model)

Then style the elements to suit your requirements

Note: either add a using statement in the view or add a reference to the <namespaces> section of web.config

Leave a Comment