MVC 中使用TreeView

为了灵活性,本例中实现是在View中完成递归逻辑,因此可以在递归过程中控制样式,内容的render

也可以选择在后端完成递归逻辑返回partial 然后在前端jquery中加class





1. 从这里下载
http://bassistance.de/jquery-plugins/jquery-plugin-treeview/


2. 将以下3个文件copy到项目中,如下所示:

MVC 中使用TreeView_第1张图片


MVC 中使用TreeView_第2张图片

3. 准备view model


public class JqTreeViewNode
    {
        public string Name { get; set; }
        public IList Children { get; set; }


        public JqTreeViewNode()
        {
            Children = new List();
        }
        public static JqTreeViewNode CreateTest()
        {
            return new JqTreeViewNode()
            {
                Name = "Root",
                Children = new List()
                {
                    new JqTreeViewNode()
                    {
                        Name = "ChildLvl1-1",
                        Children = new List
                        {
                            new JqTreeViewNode()
                            {
                                Name = "ChildLvl2-1",
                                Children = new List()
                                {
                                    new JqTreeViewNode()
                                    {
                                        Name = "ChildLvl3-1",
                                    },
                                    new JqTreeViewNode(){Name = "ChildLv3-2"},
                                    new JqTreeViewNode(){Name = "ChildLv3-3"}
                                }
                            },
                            new JqTreeViewNode(){Name = "ChildLv2-2"}
                        }
                    },
                    new JqTreeViewNode(){Name = "ChildLv1-2"}
                }
            };
        }
    }




4. controller 
public ActionResult Index()
        {


            return View(JqTreeViewNode.CreateTest());
        }




5. view 
@model WebApplication1.Controllers.JqTreeViewNode



@section scripts{
    



}


JqTreeView
@Html.Partial("JqTreeView", Model)




6. partial view (也可用display template)


@using WebApplication1.Controllers
@model WebApplication1.Controllers.JqTreeViewNode


    @{ if (Model.Children.Any()) { foreach (JqTreeViewNode item in Model.Children) {
  • @item.Name @{ if (item.Children.Any()) { @Html.Partial("JqTreeView", item) } }
  • } } }




7.查看结果


MVC 中使用TreeView_第3张图片

你可能感兴趣的:(ASP.NET,MVC,c#,编程)