@using Toink.Web.Common;
@model List<Toink.Web.Models.Category>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@{
var htmlString = string.Empty;
Html.Render(Model, (render, categories) =>
{
if (categories.Count > 0)
{
htmlString += "<ul>";
foreach (var cat in categories)
{
htmlString += "<li>";
htmlString += "<p>" + Html.Encode(cat.Name) + "</p>";
render(render, cat.Children);
htmlString += "</li>";
}
htmlString += "</ul>";
}
});
}
@*展示菜单*@
@Html.Raw(htmlString)
controller端实现逻辑
//
// GET: /User/
public ActionResult Index()
{
var model = new List<Category>
{
new Category
{
Name = "Category 1",
Children = new List<Category>
{
new Category
{
Name = "Category 1 - 1",
Children = new List<Category>()
},
new Category
{
Name = "Category 1 - 2",
Children = new List<Category>()
},
}
},
new Category
{
Name = "Category 2",
Children = new List<Category>
{
new Category
{
Name = "Category 2 - 1",
Children = new List<Category>()
},
new Category
{
Name = "Category 2 - 2",
Children = new List<Category>()
},
}
},
};
return View(model);
}
测试实体类
public class Category
{
public string Name { get; set; }
public List<Category> Children { get; set; }
}
html扩展方法
//自定义委托
public delegate void SelfApplicable<T>(SelfApplicable<T> self, T arg);
public static class HtmlExtensions
{
public static void Render<T>(this HtmlHelper helper, T model, SelfApplicable<T> f)
{
f(f, model);
}
private static Action<T> Fix<T>(Func<Action<T>, Action<T>> f)
{
return x => f(Fix(f))(x);
}
public static void Render<T>(this HtmlHelper helper, T model, Func<Action<T>, Action<T>> f)
{
Fix(f)(model);
}
}