排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:50010702506256
欢迎加群交流技术
分类:
.NET Core
写好树形需要的model,我这里前端的树形用的是jstree,按照他的格式来即可,
public class JsTreeViewModel { public int Id { get; set; } public string text { get; set; } public string icon { get; set; } public List<JsTreeViewModel> children = new List<JsTreeViewModel>(); }
写好递归树形解析方法,其实就是把数据库的数据解析成一个List<JsTreeViewModel>
public void ParseTree(List<MyNoteFile> departments, List<JsTreeViewModel> treeModels, int? parentId) { //找当前层级下级(如果parentId==null那就是第一级) List<MyNoteFile> result = departments.Where(a => a.ParentId == parentId).OrderBy(a => a.NoteFileOrder).ToList(); foreach (MyNoteFile item in result) { JsTreeViewModel treeModel = new JsTreeViewModel(); treeModel.Id = item.Id; treeModel.text = item.FileName; treeModel.icon = item.Style; //递归 ParseTree(departments, treeModel.children, treeModel.Id); treeModels.Add(treeModel); } } [HttpGet] public ContentResult GetTreeData(DTO_LoginInfo loginInfo) { List<MyNoteFile> myNoteFiles = _myNoteFileDAL.GetMyNoteFileByUserId(loginInfo.UserId); //递归解析数据 List<JsTreeViewModel> treeModels = new List<JsTreeViewModel>(); ParseTree(myNoteFiles, treeModels, null); string jsonStr = JsonConvert.SerializeObject(treeModels); return Content(jsonStr, "application/json"); }
注意:.net core3.x使用的json序列化类是System.Text.Json.JsonSerializer,据说效率快一点。但是在序列化这种树形的时候有点问题,它只能序列化一级出来,所以我这里换成了Newtonsoft.Json类
然后,数据解析好了,前端调用就很简单了
代码如下:
$("#tree_3").jstree({ "core": { "themes": { "responsive": false }, // 允许回调 "check_callback": true, 'data': { 'url': function (node) { return '/mynote/GetTreeData'; } } }, "types": { "default": { "icon": "fa fa-folder icon-state-warning icon-lg" }, "file": { "icon": "fa fa-file icon-state-warning icon-lg" } }, "state": { "key": "demo2" }, "plugins": ["contextmenu", "dnd", "state", "types"], });
效果如下:
可以换换数据库看看效果:
嘿嘿,饭做好了吃饭!
欢迎加群讨论技术,群:677373950(满了,可以加,但通过不了),2群:656732739
评价