How to Make a Single Linked List on an MVC View Page

How I'm trying to create a TreeView folder structure in MVC. I have a class file similar to 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 display this list above in MVC View. I do not know how to display single linked list data in MVC View. Any help would be appreciated.

thanks

0
source share
1 answer

You can create an extension method that uses recursion to create the <ul> and <li> elements to display the folder hierarchy

 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 the TreeViewFolder instance, and in the view

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

Then create items to suit your requirements.

Note: either add a using statement to the view, or add a link to the <namespaces> web.config section

+3
source

Source: https://habr.com/ru/post/987119/


All Articles