萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

EasyUI Tree + ASP.NET 實現權限樹/目錄樹導航完整範例

前言

jQuery EasyUI Tree 是構建樹狀導航、權限樹、組織架構的經典套件。搭配 ASP.NET 後端 (Web Forms / ASHX / MVC) 動態載入節點資料,可實現高效能、可擴展的樹狀介面。本文提供完整前後端整合範例:前端 EasyUI Tree 設定、後端 ASHX 一般處理常式輸出 JSON、資料庫遞迴查詢、節點點擊開啟分頁。

資料庫結構範例


CREATE TABLE SysMenu (
    MenuId INT PRIMARY KEY IDENTITY,
    ParentId INT NULL DEFAULT 0, -- 0 為根節點
    MenuName NVARCHAR(100) NOT NULL,
    MenuUrl NVARCHAR(500),       -- 連結網址,空白則為資料夾節點
    IconCls NVARCHAR(50),        -- EasyUI 圖示類別
    SortOrder INT DEFAULT 0,
    IsVisible BIT DEFAULT 1
);

後端:ASHX 一般處理常式 (GetTreeData.ashx)


<%@ WebHandler Language="C#" Class="GetTreeData" %>
using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Collections.Generic;
using Newtonsoft.Json; // NuGet: Newtonsoft.Json

public class GetTreeData : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "application/json; charset=utf-8";
        
        string parentIdStr = context.Request.QueryString["father"] ?? "0";
        int parentId = int.TryParse(parentIdStr, out int pid) ? pid : 0;

        List nodes = GetTreeNodes(parentId);
        string json = JsonConvert.SerializeObject(nodes);
        context.Response.Write(json);
    }

    private List GetTreeNodes(int parentId)
    {
        var list = new List();
        string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
        
        using (SqlConnection conn = new SqlConnection(connStr))
        {
            string sql = @"SELECT MenuId, MenuName, MenuUrl, IconCls, 
                          (SELECT COUNT(*) FROM SysMenu WHERE ParentId = m.MenuId) AS ChildCount
                          FROM SysMenu m 
                          WHERE ParentId = @ParentId AND IsVisible = 1
                          ORDER BY SortOrder";
            SqlCommand cmd = new SqlCommand(sql, conn);
            cmd.Parameters.AddWithValue("@ParentId", parentId);
            conn.Open();
            using (SqlDataReader dr = cmd.ExecuteReader())
            {
                while (dr.Read())
                {
                    var node = new TreeNode
                    {
                        id = dr["MenuId"].ToString(),
                        text = dr["MenuName"].ToString(),
                        iconCls = dr["IconCls"] as string ?? "icon-folder",
                        state = Convert.ToInt32(dr["ChildCount"]) > 0 ? "closed" : "open" // 有子節點預設關閉
                    };
                    
                    // 葉子節點才設定 attributes.url,資料夾節點不設定 url
                    if (node.state == "open" && !string.IsNullOrEmpty(dr["MenuUrl"] as string))
                    {
                        node.attributes = new { url = dr["MenuUrl"].ToString() };
                    }
                    list.Add(node);
                }
            }
        }
        return list;
    }

    public class TreeNode
    {
        public string id { get; set; }
        public string text { get; set; }
        public string iconCls { get; set; }
        public string state { get; set; } // "open" 或 "closed"
        public object attributes { get; set; } // 自訂屬性,如 url
        public bool checkbox { get; set; } // 權限樹用
    }

    public bool IsReusable => false;
}

前端:EasyUI Tree 初始化與事件處理


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Main.aspx.cs" Inherits="Main" MasterPageFile="~/Site.Master" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
    <!-- EasyUI CSS/JS -->
    <link rel="stylesheet" href="easyui/themes/default/easyui.css" />
    <link rel="stylesheet" href="easyui/themes/default/tree.css" />
    <link rel="stylesheet" href="easyui/themes/icon.css" />
    <script src="easyui/jquery-1.8.0.min.js"></script>
    <script src="easyui/jquery.easyui.min.js"></script>
    
    <script type="text/javascript">
        $(function () {
            $('#lefttree').tree({
                animate: true,
                checkbox: false, // 權限樹設為 true
                url: 'GetTreeData.ashx?father=0', // 根節點
                onClick: function (node) {
                    // 點擊葉子節點 (有 attributes.url) 開啟分頁
                    if (node.attributes && node.attributes.url) {
                        addTab(node.text, node.attributes.url, node.id);
                    }
                },
                onLoadSuccess: function (node, data) {
                    $('#lefttree').show(); // 載入完成顯示
                },
                onContextMenu: function (e, node) { // 右鍵選單 (可選)
                    e.preventDefault();
                    $('#treeMenu').menu('show', { left: e.pageX, top: e.pageY });
                }
            });

            // 登出確認
            $('#loginOut').click(function () {
                $.messager.confirm('系統提示', '確定要登出嗎?', function (r) {
                    if (r) location.href = 'LoginExit.ashx';
                });
            });
        });

        // 新增分頁到 EasyUI Tabs
        function addTab(title, url, id) {
            if ($('#tabs').tabs('exists', title)) {
                $('#tabs').tabs('select', title);
                // 可選:重新整理 iframe
                var tab = $('#tabs').tabs('getSelected');
                var iframe = tab.find('iframe');
                if (iframe.length) iframe[0].contentWindow.location.href = url;
            } else {
                var content = '';
                $('#tabs').tabs('add', {
                    title: title,
                    content: content,
                    closable: true,
                    id: id
                });
            }
        }
    </script>
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="BodyContent" runat="server">
    <body class="easyui-layout" style="overflow:hidden;">
        <form id="form1" runat="server">
            <!-- 北部標題列 -->
            <div region="north" split="true" border="false" style="height:60px;background:#7f99be;color:white;">
                <span style="padding-left:10px;font-size:16px;">網站後台管理系統 V1.0</span>
                <div style="float:right;padding:10px 20px 0 0;">
                    <a id="loginOut" href="#" class="head"><span class="icon icon-quit"></span>安全登出</a>
                </div>
            </div>
            
            <!-- 南部版權 -->
            <div region="south" split="true" style="height:30px;background:#D2E0F2;">
                <div class="footer">版權所有 © 2024</div>
            </div>
            
            <!-- 西部樹狀導航 -->
            <div region="west" title="導航選單" split="true" style="width:200px;">
                <ul id="lefttree"></ul>
            </div>
            
            <!-- 中央內容區 (Tabs) -->
            <div region="center" style="background:#eee;">
                <div id="tabs" class="easyui-tabs" fit="true" border="false">
                    <div title="歡迎頁" style="padding:20px;">
                        <h3>歡迎使用後台管理系統</h3>
                    </div>
                </div>
            </div>
            
            <!-- 右鍵選單 -->
            <div id="treeMenu" class="easyui-menu" style="width:150px;">
                <div id="mm-refresh">重新整理</div>
                <div class="menu-sep"></div>
                <div id="mm-expand">展開全部</div>
                <div id="mm-collapse">收合全部</div>
            </div>
        </form>
    </body>
</asp:Content>

權限樹模式 (Checkbox 多選)

若需實現角色權限配置 (勾選授權選單),修改前端設定:


$('#permTree').tree({
    checkbox: true,           // 顯示核取方塊
    cascadeCheck: true,       // 父子節點聯動
    onlyLeafCheck: false,     // 非葉子節點也可勾選
    url: 'GetPermTree.ashx?roleId=1', // 傳入角色 ID
    onCheck: function(node, checked) {
        // 可即時 AJAX 儲存權限變更
        $.post('SavePerm.ashx', { roleId: 1, menuId: node.id, checked: checked });
    }
});

// 取得已勾選節點 ID 陣列
function getCheckedIds() {
    var nodes = $('#permTree').tree('getChecked');
    return nodes.map(n => n.id).join(',');
}

後端權限樹資料來源 (GetPermTree.ashx)


// 查詢所有選單,並標記該角色已擁有的權限
string sql = @"
    SELECT m.MenuId, m.ParentId, m.MenuName, m.IconCls,
           CASE WHEN rp.RoleId IS NOT NULL THEN 1 ELSE 0 END AS Checked
    FROM SysMenu m
    LEFT JOIN RolePermission rp ON m.MenuId = rp.MenuId AND rp.RoleId = @RoleId
    WHERE m.IsVisible = 1
    ORDER BY m.SortOrder";
// 讀取後組裝 TreeNode,checked 欄位對應 node.checked (EasyUI 會自動識別)

效能優化:大量節點延遲載入 (Lazy Load)

EasyUI Tree 內建支援延遲載入:節點 `state="closed"` 時,使用者展開節點會自動發送請求 `url + "?id=" + node.id`。後端 `GetTreeData.ashx` 改為接收 `id` 參數 (而非 `father`),邏輯相同。

常見問題與解決

Q: Tree 不顯示資料?
檢查:1. ASHX 回傳 JSON 格式正確 (F12 Network 看 Response)。2. `id` 欄位為字串。3. `state` 正確設定 `open`/`closed`。4. 路徑正確 (相對路徑或絕對路徑)。
Q: 點擊節點不開啟分頁?
確認 `node.attributes.url` 存在且非空。`addTab` 函式需正確定義。檢查 `easyui.min.js` 是否載入成功。
Q: 中文亂碼?
ASHX 設定 `context.Response.ContentType = "application/json; charset=utf-8";`,資料庫連線字串無誤,檔案儲存為 UTF-8 編碼。

總結:EasyUI Tree + ASP.NET 實現樹狀導航/權限樹的關鍵在於:後端輸出符合 EasyUI 格式的 JSON (`id, text, state, iconCls, attributes, checked`),前端正確初始化 `url`、`onClick`、`checkbox` 等屬性。採用 ASHX 一般處理常式輸出 JSON 效能最佳,搭配資料庫遞迴查詢與 `state` 控制延遲載入,可支援萬級節點。權限樹模式啟用 `checkbox: true` 並處理 `onCheck` 事件即時回存。

copyright © 萬盛學電腦網 all rights reserved