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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…