下面的代码是.Net下利用递归获取所有层级的树形结构,适用于EasyUI tree树形结构使用
适用.net所有情况,演示代码是在MVC结构下的,同样适用于其他结构,
代码注释比较全,不明白的可以加群询问
[HttpPost] public JsonResult GetList() { List<info> list = bll.GetListInfo();//获取所有父级(顶级)列表 List<EasyUiTree> trees = new List<EasyUiTree>(); if (list != null && list.Count > 0) { //获取顶级节点和所有子节点 foreach (var item in list) { //获取顶级节点 EasyUiTree easyUiModel = new EasyUiTree(); easyUiModel.children = new List<EasyUiTree>(); easyUiModel.id = item.Id; easyUiModel.text = item.Name; easyUiModel.state = "open"; easyUiModel.ischecked = true; //获取子节点 var treeInfo = getTree(item.Id); if (treeInfo != null && treeInfo.Count > 0) { easyUiModel.children.AddRange(treeInfo); } trees.Add(easyUiModel); } } return this.Json(trees); } #region 获取分级后的父子数据 /// <summary> /// 构建easyUI数据 /// </summary> public class EasyUiTree { public string id { get; set; } public string text { get; set; } /// <summary> /// 'open' 或 'closed',默认是 'open' /// 如果为'closed'的时候,将不自动展开该节点 /// </summary> public string state { get; set; } public bool ischecked { get; set; } public object attributes { get; set; } public List<EasyUiTree> children { get; set; } } /// <summary> /// 递归获取数据 /// </summary> /// <param name="parentId"></param> /// <returns></returns> public List<EasyUiTree> getTree(string parentId) { //转换成Easyui数据 List<EasyUiTree> modelList = new List<EasyUiTree>(); var list = Bll.GetSonList(parentId);//根据父id,获取所有子节点数据 if (list.Count > 0) { foreach (var item in list) { EasyUiTree model = new EasyUiTree(); model.children = new List<EasyUiTree>(); model.id = item.Id; model.text = item.Name; model.state = "closed";//折叠子节点 model.ischecked = true; //递归子节点 var sonTreeInfo = getTree(item.Id); if (sonTreeInfo != null) { model.children.AddRange(sonTreeInfo); } modelList.Add(model); } } return modelList; } #endregion