Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
306 views
in Technique[技术] by (71.8m points)

asp.net mvc - 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

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...