本人是WEB初学者,近期学习使用tree时整理了一下学习笔记,以便后期总结,第一次写博文,有不对的地方希望各路大神多指教。 建立菜单树首先需要了解菜单树的结构必须包含一下四项:
ID;
Name;
ParentID;
Children;
其中children需要具有get和set方法,以便向其插入和获取子节点数据;这里可以先写一个通用实体,之后根据实际数据要求建立实体,继承通用实体;
通用实体类
public class EasyUITreeModel<T> : NotifyObject where T : class
{
public EasyUITreeModel();
public List<T> children { get; set; }
}
新建实体继承通用实体类(注意让实体可序列化)
[Serializable]
public class MenuModel : EasyUITreeModel<MenuModel>
{
public int ID { get; set; }
public string Name { get; set; }
public int PID { get; set; } //父节点
public int Level { get; set; }
public string Remark { get; set; }
}
实体建立完成后,即可写方法来拼装tree结构体,这里使用了linq语法,使用递归子节点的方法,最终返回TreeMenuList
public List<MenuModel> GetTreeMenuList()
{
var TreeMenuList = new List<MenuModel>();
var PlaneMenuList = DbSession.Query<MenuModel>().ToList();
if (PlaneMenuList == null || PlaneMenuList.Count == 0)
{
return TreeMenuList;
};
foreach (var MenuEntity in PlaneMenuList)
{
//找到顶层节点
if (MenuEntity.PID == 0)
{
TreeMenuList.Add(MenuEntity);
}
//把每个子节点加入到父节点的子节点属性中
else
{
var FatherEntity = PlaneMenuList.FirstOrDefault(Entity => Entity.ID == MenuEntity.PID);
if (FatherEntity != null)
{
FatherEntity.children.Add(MenuEntity);
}
}
};
return TreeMenuList;
}