How to render singly Linked list in MVC View page

As I am trying to create a TreeView folder structure in MVC. I have class file something like the below.

Class File

 public class TreeViewFolder
 {
    public string FolderPath { get; set; }
    public string FolderName { get; set; }
    public List<TreeViewFolder> MyTreeList { get; set; }
 }

I need to render that above list in MVC View. I have no idea how to render single linked list data in MVC View. Any help will be appreciated.

Thanks


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