最近在做项目的过程中需要用到Tree插件,所以找了一堆Tree发现LayUI的Tree样式比较好看,所以开始搞!
1.Layui部分
1.1 首先引用文件是必不可少的:(依赖于Jquery)
<link type="text/css" rel="Stylesheet" href="~/Content/js/plugins/layui-v2.5.4/layui-v2.5.4/layui/css/layui.css" /><script type="text/javascript" src="~/Content/js/plugins/layui-v2.5.4/layui-v2.5.4/layui/layui.js"></script>
1.2 Js部分
function SetTree() { layui.use('tree', function () { var tree = layui.tree; $.ajax({ type: "POST", url: "/CmdSite/GetTreeEntity", data: {}, success: function (result) { var inst1 = tree.render({ elem: '#menuTree', id: 'tree', data: JSON.parse(result), isJump: true,//以下配置项参考Layui Tree 官方文档 showLine: true, onlyIconControl: true, accordion:false, click: function (obj) { var data = JSON.stringify(obj.data);//这里是点击获得数据 var jsonData = JSON.parse(data); } }); }, error: function (e) { console.log(e.status); console.log(e.responseText); } }); }); }
1.3 Html部分
<div id="menuTree" class="demo-tree-more"></div>
这就很省事了!
2. .Net部分
2.1 你得有个实体类
//这里面字段最好对应文档里面的
public class treeEntity { /// <summary> /// 主键ID /// </summary> public int id { get; set; } /// <summary> /// 父ID /// </summary> public string pid { get; set; } /// <summary> /// 名称 /// </summary> public string title { get; set; } /// <summary> /// 图标 /// </summary> public string icon { get; set; } /// <summary> /// 链接 /// </summary> public string url { get; set; } /// <summary> /// 排序 /// </summary> public string sort { get; set; } /// <summary> /// 是否展开 /// </summary> public bool spread { get;set;} /// <summary> /// 子节点 /// </summary> public List<treeEntity> children { get; set; } }
2.2 遍历拼接
/// <summary> /// 获得Tree实体(我只做了二级的 有需要的可以自己改成递归) /// </summary> /// <returns></returns> public static string GetTreeEntityJson() { var CategoryList = Dao.BLL.MenuCategory.QueryListByFMcid(0); var menuList = new List<treeEntity>(); foreach (var item in CategoryList) { treeEntity tree = new treeEntity { icon = item.icon, id = item.mcid, title = item.name, sort = item.sort.ToString(), pid = "0", url = "", spread=true, }; var menuEntityList = Dao.BLL.Menu.QueryListByMcid(item.mcid); var childrenList = new List<treeEntity>(); foreach (var ChildItem in menuEntityList) { treeEntity ChindrenTree = new treeEntity { icon = "fa fa-diamond", id = (int)ChildItem.menu, title = ChildItem.name, sort = ChildItem.sort.ToString(), pid = ChildItem.mcid.ToString(), url = "", children=null, spread = true, }; childrenList.Add(ChindrenTree); } tree.children = childrenList; menuList.Add(tree); } var menuJson = Newtonsoft.Json.JsonConvert.SerializeObject(menuList); return menuJson;
2.3 返回Json
public string GetTreeEntity() { return JQLY.Helper.MenuHelper.GetTreeEntityJson(); }
这样就搞定了!
LayUI地址:https://www.layui.com
来源:https://www.icode9.com/content-4-360651.html联系客服