我正在尝试在MVC中创建TreeView文件夹结构。我有类文件,如下所示。
类文件
public class TreeViewFolder
{
public string FolderPath { get; set; }
public string FolderName { get; set; }
public List<TreeViewFolder> MyTreeList { get; set; }
}
我需要在MVC View中呈现上面的列表。我不知道如何在MVC View中呈现单个链表数据。任何帮助将不胜感激。
由于
答案 0 :(得分:3)
您可以创建一个扩展方法,使用递归来构建<ul>
和<li>
元素以显示文件夹的层次结构
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();
}
}
然后在您的控制器中,初始化并填充TreeViewFolder
的实例,并在视图中
@model TreeViewFolder
....
@Html.FolderTree(Model)
然后根据您的要求设计元素的样式
注意:要么在视图中添加using
语句,要么添加对<namespaces>
的{{1}}部分的引用