SQL server + ASP.NET MVP + Jquery EasyUI實現樹形節點的增刪改查
最近在做專案時遇到了這樣一個需求,就是做一個系統首頁左側選單的樹形節點的管理。專案後臺資料庫使用的是SQL server 2008,後端框架使用的是微軟的ASP.NET MVC5,前端框架使用的是Jquery EasyUI。接下來我就講解一下如何實現樹形節點的管理功能。
先看一下什麼是樹形節點 如上圖素所示,這就是樹形節點。
模型
資料庫表結構的設計
首先我們先講解一下如何設計資料庫的表結構,以便方便地儲存和查詢這些節點資料。我的設計是這樣的: 也就是說,這張表只有3個欄位:節點的id(id),節點名稱(name),父節點id(parent_node_id)。最外層節點沒有父節點,所以它的parent_node_id這個欄位的值為0,當我們要查詢最外層節點時,只要查詢parent_node_id=0的節點就好了。通過這3個欄位,就構建了一個層級關係。
類的設計
類的程式碼設計如下:
public class Node { public Node() { } public Node(int id, string text, int parent_node_id, List<Node> children) { this.id = id; this.text = text; this.parent_node_id = parent_node_id; this.children = children; } public int id { get; set; } public string text { get; set; } public int parent_node_id { get; set; } public List<Node> children; }
一般來講,類的屬性和表的欄位應該是一一對應的,但是這裡多了一個屬性chirldren
,這個屬性是List
型別,用來儲存當前節點的子節點,當一個節點沒有子節點,即它是葉子節點時,它的children
是一個空的列表。children
屬性的作用在後面查詢的時候就會顯現出來了。
查詢
表類設計好了,先手動往裡面新增一些資料,然後來看怎麼查詢節點。 為了讓EasyUI將節點以樹形結構展示出來,我們必須向前端傳遞一個JSON格式的字串,這個JSON格式的字串應該長這樣: 我採取的辦法是,先一次性將節點資料查詢出來,存到DataTable中,然後採用遞迴的方式,一層層地將資料取出來。 程式碼如下:
public static void getChildrenNode(DataTable dt, int id, Node node) { DataRow[] children_node = dt.Select("parent_node_id = " + id); //找到node的所有的子節點 for (int i = 0; i < children_node.Length; i++) { //依次將每一個子節點放入到node的children中 Node nd = new Node((int)children_node[i]["id"], (string)children_node[i]["name"], (int)children_node[i]["parent_node_id"], new List<Node>()); node.children.Add(nd); //然後獲得子節點的子節點 getChildrenNode(dt, nd.id, nd); } } public JsonResult getTreeJson() { //初始化一個空列表,用來存放所有的節點 List<Node> nodes = new List<Node>(); //從資料庫中查詢所有資料,SqlHelper是我自己寫的一個工具類,可以將它換成別的 DataTable dt = SqlHelper.ExecuteTable("select * from node", null); DataRow[] root_node = dt.Select("parent_node_id = " + 0); //找到所有的根節點 for (int i = 0; i < root_node.Length; i++) { Node nd = new Node((int)root_node[i]["id"], (string)root_node[i]["name"], (int)root_node[i]["parent_node_id"], new List<Node>()); nodes.Add(nd); getChildrenNode(dt, nd.id, nd); } //將列表中的資料轉成JSON字串的格式,傳遞到前端 return Json(nodes, JsonRequestBehavior.AllowGet); }
由於是網站首頁左側選單,所以要在_Layout.cshtml中接收JSON字串。參考EasyUI的教程,只需在_Layout.cshtml中引入相應的包,然後加上這樣一個標籤
<ul id="tt" class="easyui-tree" url="/Home/getTreeJson"></ul>
就可以顯示屬性節點了。其中/Home/getTreeJson
是上面那個方法在專案中的路徑。