1.生成树节点对象
/// <summary> /// 生成树的节点 /// </summary> public class TreeNode { public TreeNode() { Children = new List<TreeNode>(); } [JsonProperty("id")] public string Id { get; set; } [JsonProperty("text")] public string Text { get; set; } /// <summary> /// open/closed /// </summary> [JsonProperty("state", NullValueHandling = NullValueHandling.Ignore)] public string State { get; set; } [JsonProperty("checked", NullValueHandling = NullValueHandling.Ignore)] public bool? IsChecked { get; set; } /// <summary> /// Attributes对应的为json字符串 /// </summary> [JsonProperty("attributes", NullValueHandling = NullValueHandling.Ignore)] public dynamic Attributes { get; set; } [JsonProperty("children", NullValueHandling = NullValueHandling.Ignore)] public List<TreeNode> Children { get; set; } }
其中应用了Newtonsoft.Json的属性,可以在生成Json时去掉一下不必要的属性。
2.递归生成树对象
/// <summary> /// 递归生成数 /// </summary> /// <param name="rootNode">树的根节点</param> /// <param name="listModules">生成数的所有节点</param> /// <param name="parentId">父节点id</param> private void GetTreeByList(TreeNode rootNode, List<sys_module> listModules, string parentId) { var listParent = Sys_Module_B.GetChildrenByParentId(listModules, parentId); foreach (var item in listParent) { var listChild = Sys_Module_B.GetChildrenByParentId(listModules, item.ModuleID); TreeNode tn = new TreeNode(); tn.Id = item.ModuleID; tn.Text = item.ModuleName + (string.IsNullOrEmpty(item.FunctionCode) ? "" : ("(" + item.FunctionCode + ")")); tn.State = "open"; tn.Attributes = new {GrantedCode =""};//默认设置
if (listChild != null) { GetTreeByList(tn, listModules, item.ModuleID, dsRole); } rootNode.Children.Add(tn); } }
这个方法递归生成了树对象。
3.获取子节点
/// <summary> /// 根据父节点,找到所有子菜单module /// </summary> /// <param name="listModules"></param> /// <param name="parentId"></param> /// <returns></returns> public static List<sys_module> GetChildrenByParentId(List<sys_module> listModules, string parentId) { List<sys_module> children = (from lm in listModules where lm.ParentModuleID == parentId select lm).ToList(); return children; }
4.转换为json
//获取所有的菜单模块节点 List<sys_module> list = Sys_Module_B.SelectAllModules(); TreeNode node = new TreeNode(); GetTreeByList(node, list, moduleId); string toJson = JsonTools.SerializeObject(node.Children);
记录一下~