如何在 MVC 视图页面中呈现单链表 [英] How to render singly Linked list in MVC View page
问题描述
因为我试图在 MVC 中创建一个 TreeView 文件夹结构.我有类似下面的类文件.
类文件
公共类 TreeViewFolder{公共字符串 FolderPath { 获取;放;}公共字符串 FolderName { 获取;放;}公共列表MyTreeList { 获取;放;}}
我需要在 MVC 视图中呈现上面的列表.我不知道如何在 MVC 视图中呈现单链表数据.任何帮助将不胜感激.
谢谢
你可以创建一个扩展方法,使用递归来构建
和 显示文件夹层次结构的元素
公共静态类FolderTreeExtensions{public static MvcHtmlString FolderTree(这个 HtmlHelper 助手,TreeViewFolder 文件夹){返回 MvcHtmlString.Create(TreeLeaf(folder));}//递归函数私有静态字符串 TreeLeaf(TreeViewFolder 文件夹){StringBuilder html = new StringBuilder();TagBuilder div = new TagBuilder("div");div.InnerHtml = 文件夹.文件夹名称;html.Append(div.ToString());if (folder.MyTreeList != null){foreach(文件夹中的TreeViewFolder子文件夹.MyTreeList){html.Append(TreeLeaf(子文件夹));}}TagBuilder item = new TagBuilder("li");item.InnerHtml = html.ToString();TagBuilder container = new TagBuilder("ul");container.InnerHtml = item.ToString();返回 container.ToString();}}
然后在您的控制器中,初始化并填充TreeViewFolder
的实例,并在视图中
@model TreeViewFolder....@Html.FolderTree(模型)
然后设计元素以满足您的要求
注意:要么在视图中添加一个 using
语句,要么添加对 web.config
<的
部分的引用/p>
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
这篇关于如何在 MVC 视图页面中呈现单链表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!