分类:
.NET Core
前言
你别认输,天黑之后就是日出
生活有望穿秋水的等待,也会有意想不到的惊喜!Come on! smile girl !
最近在学习根据数据库无限动态添加树形,从中涉及到啦递归算法
我们首先得下载Layui的Js和css文件,
看下图操作
下面的代码,都是在里面clone的
<link href="~/lib/layui/css/layui.css" rel="stylesheet" /> <script src="~/lib/layui/layui.js"></script> <script src="~/lib/jquery/dist/jquery.js"></script> <div id="test12" class="demo-tree-more" style="margin-top:60px;"></div> <script> layui.use(['tree', 'util'], function () { var tree = layui.tree , layer = layui.layer , util = layui.util $.get('/TreeModel/GetTree', function (data) { //基本演示 tree.render({ elem: '#test12' , data: data , showCheckbox: true //是否显示复选框 , id: 'demoId1' , isJump: true //是否允许点击节点时弹出新窗口跳转 , click: function (obj) { var data = obj.data; //获取当前点击的节点数据 layer.msg('状态:' + obj.state + '<br>节点数据:' + JSON.stringify(data)); } }); }) }); </script>
我们得建立一个实体模型,方便等会使用需要
public class TreeModel { public int Id { get; set; } public string Title { get; set; } public List<TreeModel> children = new List<TreeModel>(); } }
//接下来就是生成数据实体类库啦,(记得把数据库名换成自己数据库的名字)
Scaffold-DbContext "Server=.;Database=Food;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
public class TreeModelController : Controller { public void ParseTree(List<Department> departments,List<TreeModel> treeModels,int ? ParentId) { //找当前层级下级(如果paretId==null就是第一级) List<Department> departmentslist = departments.Where(a => a.ParentId == ParentId).ToList(); foreach (Department item in departmentslist) { TreeModel treeModel = new TreeModel(); treeModel.Id = item.Id; treeModel.Title = item.DepartName; //部门名称 treeModels.Add(treeModel); //递归 ParseTree(departments,treeModel.children,treeModel.Id); } } [HttpGet] public JsonResult GetTree() { treemodelContext treemodel = new treemodelContext(); List<Department> departments = treemodel.Department.ToList(); List<TreeModel> treeModels = new List<TreeModel>(); ParseTree(departments,treeModels,null); return Json(treeModels); }
评价