可编辑树Ztree的使用(包括对后台数据库的增删改查)

时间:2021-12-06 12:04:37

找了很多网上关于Ztree的例子和代码才搞定。

首先,关于Ztree的代码不介绍了,网上下载之后,引用下列四个文件就能使用了。

 可编辑树Ztree的使用(包括对后台数据库的增删改查)

 

可编辑树Ztree的使用(包括对后台数据库的增删改查)

 

1.关于配置选项。主要通过回调函数来实现向后台发送数据,实现增删改查。

 

 1  var setting = {
 2         view: {
 3             addHoverDom: addHoverDom,//显示操作图标
 4             removeHoverDom: removeHoverDom,//移除图标
 5             selectedMulti: false
 6         },
 7         check: {
 8             enable: true
 9         },
10         data: {
11             simpleData: {
12                 enable: true
13             }
14         },
15         callback: {
16             onRename: zTreeOnRename,//修改
17             onRemove: zTreeOnRemove,//删除
18             onClick: zTreeOnClickRight,
19 
20         },
21         edit: {
22             enable: true,
23             showRemoveBtn: true,
24             showRenameBtn: true,
25             removeTitle: "删除",
26             renameTitle: "修改"
27         }
28     };


 $(document).ready(function () {
        $.ajax({
            url: "GetZtreeJson",
            data: { ProjectId: "@ViewBag.ProjectId" },
            type: "post",
            dataType: "json",
            success: function (data) {
                $.fn.zTree.init($("#test"), setting, data);//实现加载树的方法
            }
        })
        $("#btnReturn").click(function () {
            window.parent.frameReturnByClose();
        });
        //$.fn.zTree.init($("#treeDemo"), setting, zNodes);
    });

    var newCount = 1;
    function addHoverDom(treeId, treeNode) {
        var sObj = $("#" + treeNode.tId + "_span");
        if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0) return;
        var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
            + "' title='add node' onfocus='this.blur();'></span>";
        sObj.after(addStr);
        var btn = $("#addBtn_" + treeNode.tId);
        if (btn) btn.bind("click", function () {
            var zTree = $.fn.zTree.getZTreeObj("test");
 //增加节点的方法
            $.ajax({
                url: "AddNode",
                data: { ParentId: treeNode.id },
                type: "post",
                success: function (data) {
                    if (data.message == "success") {
//此方法是js在前段增加节点方法,一定要通过后台返回的id来增加,不然新增的节点会出现节点id为null的问题 zTree.addNodes(treeNode, { id: data.id, ParentId: treeNode.id, name: "new node" + (newCount++) }); } else { $.messageBox5s('@Resource.Tip', "新增节点失败!联系管理员!"); } } }) return false; }); };
//删除节点
function zTreeOnRemove(event, treeId, treeNode) { { $.ajax({ url: "DeleteNode", type: "post", data: { NodeId: treeNode.id }, success: function (data) { if (data == "success") { } else { $.messageBox5s('@Resource.Tip', "删除节点失败!联系管理员!"); } } }) } } function removeHoverDom(treeId, treeNode) { $("#addBtn_" + treeNode.tId).unbind().remove(); }; //修改节点 function zTreeOnRename(event, treeId, treeNode) { $.ajax({ url: "EditNode", type: "post", data: { NodeId: $.trim(treeNode.id), name: treeNode.name }, success: function (data) { if (data != "success") { $.messageBox5s('@Resource.Tip', "修改节点失败!联系管理员!"); } } }) }; // 树的单击事件 function zTreeOnClickRight(event, treeId, treeNode) { var treeid = treeNode.id; $("#hidId").val(treeid); $("#ifm").attr("src", "FileView?NodeId=" + treeid); } function treeShow(data) { zTreeObj = $.fn.zTree.init($("#test"), setting, data); zTreeObj.expandAll(true); }

2.后台处理的方法。。我项目中是使用C#代码写的,mvc框架

 

 

 1  [Description("项目资料-树形")]
 2         [KeyCode(Name = "Tree")]
 3         [IsModule]
 4         [SupportFilter(ActionName = "Tree")]
 5         public ActionResult TreeIndex(Guid ProjectId)
 6         {
 7 
 8             ViewBag.ProjectId = ProjectId;
 9             var ProjectCode = IProjectContract.GetProjectInputById(ProjectId).ProjectCode;
10             string count = ProjectResourceContract.CountNumber(ProjectCode);
11             ViewBag.Count = count;
12             return View();
13         }
14      
15         public JsonResult GetZtreeJson(Guid ProjectId)
16         {
17             var list = ProjectResourceContract.GetNodeJsonByProject(ProjectId);
18 
19 
20             return Json((from p in list
21                          select new
22                          {
23                              id = p.Id,
24                              pId = p.pid,
25                              open = "true",
26                              name = p.name
27                          }).ToList());
28         }
29         public JsonResult AddNode(string ParentId)
30         {
31             int sort = ProjectResourceContract.GetLastNodeSortFormParent(ParentId);
32             //string nodeid = ProjectResourceContract.GetCurrentNewNodeId(ParentId);
33             if (sort == 1)
34             {
35                 var node = ProjectResourceContract.GetNodeByNodeId(ParentId);
36                 node.type = "1";
37                 ProjectResourceContract.EditNode(ParentId, node.type);
38             }
39             Guid nodeId = Guid.NewGuid();
40             var ProjectCode = ProjectResourceContract.GetNodeByNodeId(ParentId).ProjectCode;
41             var result = ProjectResourceContract.AddNode(new TB_Project_Nodes()
42             {
43                 Id = nodeId,
44                 name = "New Node" + sort,
45                 type = "2",
46                 pid = ParentId,
47                 sort = sort,
48                 state = "true",
49                 ProjectCode = ProjectCode,
50             });
51             if (result.Successed)
52             {
53                 return Json(new { message = "success", id = nodeId });
54             }
55             else
56             {
57                 return Json("error");
58             }
59         }
60         public JsonResult DeleteNode(string NodeId)
61         {
62             var result = ProjectResourceContract.DeleteNode(NodeId);
63             if (result.Successed)
64             {
65                 return Json("success");
66             }
67             else
68             {
69                 return Json("error");
70             }
71         }
72         public JsonResult EditNode(string NodeId, string name, string path = "", string ProjectCode = "")
73         {
74             OperationResult result;
75             if (!string.IsNullOrEmpty(path))
76             {
77                 path = path.TrimEnd('+');
78 
79                 path = "UpDir/" + ProjectCode + "/施工资料/" + path;
80                 result = ProjectResourceContract.EditNode(NodeId, name, path);
81             }
82             else
83             {
84                 result = ProjectResourceContract.EditNode(NodeId, name, "");
85             }
86             if (result.Successed)
87             {
88                 return Json("success");
89             }
90             else
91             {
92                 return Json("error");
93             }
94         }

 

我项目中的情况是需要用ztree来实现创建目录,然后上传施工资料的方法。所以,projectid字段,大家不需要在意。是项目的id

 

3.给大家看一下我的数据库字段设计,附上关于增删改查操作数据库的代码。

可编辑树Ztree的使用(包括对后台数据库的增删改查)

 

可编辑树Ztree的使用(包括对后台数据库的增删改查)

 

 这里*节点的pid为0,其次projectcode是我项目中使用到的,可以不用考虑。state本来是用于ztree中open配置信息用的。默认展开节点的配置。

type是我用于判断此节点是否包是文件节点用的。(包含子节点的为文件夹节点,没有子节点的就是文件节点)

 

4.serveices代码

  1  //获取树所有节点显示
  2         public List<TB_Project_Nodes> GetNodeJsonByProject(Guid ProjectId)
  3         {
  4 
  5 
  6             var project = ProjectsRepository.GetByKey(ProjectId);
  7             string TopNode = project.ProjectCode;
  8             List<TB_Project_Nodes> ALLLIST = NodesRepository.Entities.Where(t => t.ProjectCode == TopNode).ToList();
  9             //var top = NodesRepository.Entities.FirstOrDefault(t => t.Id.ToString() == TopNode);
 10             TB_Project_Nodes top = ALLLIST.FirstOrDefault(t => t.ProjectCode == TopNode&&t.pid=="0");
 11             if (top == null)//第一次创建
 12             {
 13                 TB_Project_Nodes pn = new TB_Project_Nodes() { ProjectCode = TopNode, Id = Guid.NewGuid(), type = "1", pid = "0", sort = 1, name = project.ProjectName, state = "true" };
 14                 NodesRepository.Insert(pn);
 15                 return new List<TB_Project_Nodes>() { pn };
 16             }
 17             else//存在*节点
 18             {
 19 
 20                 //List<TB_Project_Nodes> nodes = NodesRepository.Entities.Where(t => t.pid == TopNode).OrderBy(t => t.sort).ToList();//*节点下面的一级节点
 21                 List<TB_Project_Nodes> nodes = ALLLIST.Where(t => t.pid == top.Id.ToString()).OrderBy(t => t.sort).ToList();//*节点下面的一级节点
 22 
 23                 if (nodes.Count <= 0)//没有子节点
 24                 {
 25                     return new List<TB_Project_Nodes>() { top };
 26                 }
 27                 else//存在子节点,遍历所有的子节点
 28                 {
 29 
 30                     List<TB_Project_Nodes> LIST = new List<TB_Project_Nodes>();
 31                     LIST.Add(top);
 32                     LIST.AddRange(nodes); //添加一级节点
 33            
 34                     LIST = Test(nodes, LIST, ALLLIST);
 35 
 36                     return LIST;
 37                 }
 38 
 39             }
 40 
 41         }
 42         //递归函数---把所有二级节点以及以下所有节点获取
 43         public List<TB_Project_Nodes> Test(List<TB_Project_Nodes> list, List<TB_Project_Nodes> LIST, List<TB_Project_Nodes> ALLLIST)
 44         {
 45             List<TB_Project_Nodes> NEWLIST = new List<TB_Project_Nodes>();
 46             foreach (var item2 in list)
 47             {
 48                 var secondNodes = ALLLIST.Where(t => t.pid == item2.Id.ToString()).OrderBy(t => t.sort).ToList();
 49                 if (secondNodes.Count > 0)
 50                 {
 51 
 52                     NEWLIST.AddRange(secondNodes);
 53                 }
 54             }
 55             LIST.AddRange(NEWLIST);
 56             //已经添加完本级节点
 57             //添加下一级节点
 58             if (NEWLIST.Count > 0)
 59             {
 60                 Test(NEWLIST, LIST, ALLLIST);
 61             }
 62             return LIST;
 63         }
 64         //增加节点信息
 65         public OperationResult AddNode(TB_Project_Nodes node)
 66         {
 67 
 68             int result = NodesRepository.Insert(node);
 69             if (result == 0)
 70             {
 71                 return new OperationResult(OperationResultType.Error, "error");
 72             }
 73             else
 74             {
 75                 return new OperationResult(OperationResultType.Success, "success");
 76             }
 77 
 78         }
 79         /// <summary>
 80         /// 修改节点类型
 81         /// </summary>
 82         /// <param name="NodeId"></param>
 83         /// <param name="type"></param>
 84         /// <returns></returns>
 85         public OperationResult EditNode(string NodeId, string type)
 86         {
 87             var node = NodesRepository.Entities.FirstOrDefault(t => t.Id.ToString() == NodeId);
 88             node.type = type;
 89             int result = NodesRepository.Update(node);
 90             if (result == 0)
 91             {
 92                 return new OperationResult(OperationResultType.Error, "error");
 93             }
 94             else
 95             {
 96                 return new OperationResult(OperationResultType.Success, "success");
 97             }
 98         }
 99 
100         /// <summary>
101         /// 获取父级节点下面最大的一个排序+1
102         /// </summary>
103         /// <param name="ParentId"></param>
104         /// <returns></returns>
105 
106         public int GetLastNodeSortFormParent(string ParentId)
107         {
108             var list = NodesRepository.Entities.Where(t => t.pid == ParentId).OrderByDescending(t => t.sort).ToList();
109             if (list.Count <= 0)
110             {
111                 return 1;
112             }
113             else
114             {
115                 return list[0].sort + 1;
116             }
117         }
118 
119         /// <summary>
120         /// 删除此节点时候,要把下面所有子节点删除
121         /// </summary>
122         /// <param name="NodeId"></param>
123         /// <returns></returns>
124         public OperationResult DeleteNode(string NodeId)
125         {
126             List<TB_Project_Nodes> ALLLIST = NodesRepository.Entities.ToList();
127             // var node = NodesRepository.Entities.FirstOrDefault(t => t.Id.ToString() == NodeId);
128             var node = ALLLIST.FirstOrDefault(T => T.Id.ToString() == NodeId);
129             //获取下面的所有子节点
130             List<TB_Project_Nodes> LIST = new List<TB_Project_Nodes>();
131             LIST.Add(node);
132             var list = ALLLIST.Where(t => t.pid == NodeId).ToList();
133             if (list.Count > 0)
134             {
135                 LIST.AddRange(list);
136                 LIST = Test(list, LIST, ALLLIST);
137             }
138             for (int i = LIST.Count - 1; i >= 0; i--)
139             {
140                 try
141                 {
142                     int result = NodesRepository.Delete(LIST[i].Id);
143                 }
144                 catch (Exception ex)
145                 {
146                     return new OperationResult(OperationResultType.Error, "error");
147                     throw ex;
148                 }
149 
150             }
151 
152             return new OperationResult(OperationResultType.Success, "success");
153 
154         }