欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-12-16 11:19:02
找了很多网上关于Ztree的例子和代码才搞定。 首先,关于Ztree的代码不介绍了,网上下载之后,引用下列四个文件就能使用了。 1.关于配置选项。主要通过回调函数来实现向后台发送数据,实现增删改查。 2.后台处理的方法。。我项目中是使用C#代码写的,mvc框架 我项目中的情况是需要用ztree来实现 ......

找了很多网上关于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         }