asp.net中利用jquery zTree非同步載入資料

暖楓無敵發表於2015-07-03

jquery zTree需要使用的js和css,可以從下列地址獲取:http://download.csdn.net/detail/taomanman/8865543

執行效果如下圖所示:


1、用於獲取JSON資料的程式碼:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="RegionData.aspx.cs" Inherits="AT.Web.Ajax.RegionData" %>

using AT.Business.DAL;
using AT.Business.IDAO;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace AT.Web.Ajax
{
    public partial class RegionData : System.Web.UI.Page
    {
        private AT_System_IDAO systemidao = new AT_System_Dal();

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                //取得前臺ajax請求的方法名稱
                string ajaxMethod = Request["ajaxMethod"].ToString();
                System.Reflection.MethodInfo method = this.GetType().GetMethod(ajaxMethod);
                if (method != null)
                {
                    //通過方法名稱指向對應的方法
                    method.Invoke(this, new object[] { });
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                Response.End();
            }

        }

        /// <summary>
        /// 非同步載入當前節點的子節點
        /// </summary>
        public void AnsyData()
        {
            List<object> lsNode = new List<object>();
            try
            {
                string parentId = Request.Params["id"];
                DataTable dtRegion = this.systemidao.GetRegionList();
                DataView dv = new DataView(dtRegion);
                dv.RowFilter = "PRegion_ID = '" + parentId + "'";
                lsNode = getList(dv);
                Response.Write(JsonConvert.SerializeObject(lsNode));
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 判斷當前節點是否還有子節點
        /// </summary>
        /// <param name="ParentId">父節點Id</param>
        /// <returns>bool型別</returns>
        public bool isParentTrue(string ParentId)
        {
            try
            {
                DataTable dtRegion = this.systemidao.GetRegionList();
                DataView dv = new DataView(dtRegion);
                dv.RowFilter = "PRegion_ID = '" + ParentId + "'";
                return dv.Count >= 1 ? true : false;
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 初始化第一次節點載入
        /// </summary>
        public void FirstAnsyData()
        {
            try
            {
                DataTable dtRegion = this.systemidao.GetRegionList();
                DataView dv = new DataView(dtRegion);
                dv.RowFilter = " PRegion_ID = '0' ";
                List<object> lsNode = new List<object>();
                lsNode = getList(dv);
                //用到了Newtonsoft.dll 轉化成Json格式
                Response.Write(JsonConvert.SerializeObject(lsNode));
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 把資料形式轉換成zTree的json資料格式
        /// </summary>
        /// <param name="table"></param>
        /// <returns></returns>
        public List<object> getList(DataView table)
        {
            try
            {
                List<object> lsNode = new List<object>();
                bool isParent = true;
                foreach (DataRowView drv in table)
                {
                    var ParentId = string.IsNullOrEmpty(drv["PRegion_ID"].ToString()) ? "0" : drv["PRegion_ID"].ToString();
                    if (isParentTrue(drv["Region_ID"].ToString()))
                    {
                        isParent = true;
                    }
                    else
                    {
                        isParent = false;
                    }
                    var zTreeData = new
                    {
                        id = drv["Region_ID"],
                        pId = string.IsNullOrEmpty(ParentId) ? "0" : ParentId,
                        name = drv["Region_Name"],
                        isParent = isParent
                    };
                    lsNode.Add(zTreeData);
                }
                return lsNode;
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}

2、用於展示zTree目錄樹的頁面程式碼:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="AT.Web.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>zTree樹形示例</title>
    <link href="Themes/Styles/zTreeStyle/zTreeStyle.css" rel="stylesheet" />
    <script src="Themes/Scripts/jquery-1.8.2.min.js" type="text/javascript"></script>
    <script src="Themes/Scripts/artDialog/artDialog.source.js" type="text/javascript"></script>
    <script src="Themes/Scripts/artDialog/iframeTools.source.js" type="text/javascript"></script>
    <script src="Themes/Scripts/FunctionJS.js" type="text/javascript"></script>
    <script type="text/javascript">
    </script>
    <script src="Themes/Scripts/jquery.ztree.core-3.5.min.js"></script>
    <script type="text/javascript">
        var zNodes;
        var zTree;
        //setting非同步載入的設定
        var setting = {
            async: {
                enable: true, //表示非同步載入生效
                url: "Ajax/RegionData.aspx", // 非同步載入時訪問的頁面
                autoParam: ["id"], // 非同步載入時自動提交的父節點屬性的引數
                otherParam: ["ajaxMethod", 'AnsyData'], //ajax請求時提交的引數
                type: 'post',
                dataType: 'json'
            },
            checkable: true,
            showIcon: true,
            showLine: true, // zTree顯示連線線
            data: {  //用pId來標識父子節點的關係
                simpleData: {
                    enable: true
                }
            },
            expandSpeed: "", // 設定 zTree 節點展開、摺疊的動畫速度,預設為"fast",""表示無動畫
            callback: { // 回撥函式
                onClick: zTreeOnClick, // 單擊滑鼠事件
                asyncSuccess: zTreeOnAsyncSuccess //非同步載入成功事件
            }
        };

        $(document).ready(function () {
            InitRegion();
            $.fn.zTree.init($("#treeDemo"), setting, zNodes);
        });

        //初始化載入節點
        function InitRegion() {
            $.ajax({
                url: 'Ajax/RegionData.aspx',
                type: 'post',
                dataType: 'json',
                async: false,
                data: { 'ajaxMethod': 'FirstAnsyData' },
                success: function (data) {
                    zNodes = data;
                }
            });
        };

        //單擊時獲取zTree節點的Id,和value的值
        function zTreeOnClick(event, treeId, treeNode, clickFlag) {
            var treeValue = treeNode.id + "," + treeNode.name;
            //單擊給文字框賦值
            var Id = treeNode.pId;
            var v = "";
            if (Id == '' || Id == undefined || Id == null) {
                v = treeNode.name + " - 父節";
            }
            else {
                v = treeNode.name + " - 子節";
            }
            top.Role_Form.Get_Region_ID(treeNode.id, v);
            //雙擊的話關閉彈出框
            //OpenClose();
            alert(v + "," + treeNode.name);
        };

        function zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <ul id="treeDemo" class="ztree"></ul>
    </form>
</body>
</html>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace AT.Web
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
    }
}







相關文章