zTree结合Asp.net实现异步加载数据(写的可能有点简单....)

时间:2022-11-28 19:43:41

前台html标签(asyncData.aspx页面....用于展示的页面)

<head runat="server">
    <title></title>
    <link href="JQuery%20ZTree/css/demo.css" rel="stylesheet" type="text/css" />
    <link href="JQuery%20ZTree/css/zTreeStyle/zTreeStyle.css" rel="stylesheet" type="text/css" />
    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script src="JQuery%20ZTree/js/jquery.ztree.core-3.5.js" type="text/javascript"></script>
    <script type="text/javascript">
            var zNodes;
             var zTree;
            //setting异步加载的设置
            var setting = {
                async: {
                enable:true, //表示异步加载生效
                url: "WebData.aspx", // 异步加载时访问的页面
                autoParam: ["id"], // 异步加载时自动提交的父节点属性的参数
                otherParam:["ajaxMethod",'AnsyData'], //ajax请求时提交的参数
                type:'post',
                dataType:'json'
               },
                checkable: true,
                showIcon: true,
                showLine: true, // zTree显示连接线
                data: {  //data的设置表示json数据是以这种格式显示的     zNodes = [{ "id": 1, "pId": 0, "name": "zhangsan" } ,{ "id": 2, "pId": 1, "name": "lisi" }]; 用pId来标识父子节点的关系
                simpleData: {
                    enable: true
                }
               },
                expandSpeed: "", // 设置 zTree 节点展开、折叠的动画速度,默认为"fast",""表示无动画
                callback: { // 回调函数
                    onClick: zTreeOnClick, // 单击鼠标事件
                    asyncSuccess: zTreeOnAsyncSuccess //异步加载成功事件
                }
            };
            $(document).ready(function () {
                Inint();
                $.fn.zTree.init($("#treeDemo"), setting, zNodes);
           });
            //初始化加载节点
            function Inint(){
                $.ajax({
                    url: 'WebData.aspx',
                    type: 'post',
                    dataType: 'json',
                     async: false,
                    data: { 'ajaxMethod': 'FirstAnsyData' },
                    success: function (data) {
                        zNodes = data;
                    }
                });
            };
            //单击时获取zTree节点的Id,和value的值
            function zTreeOnClick(event, treeId, treeNode, clickFlag) {
                treeValue = treeNode.id + "~" + treeNode.name;
                alert(treeNode.id + "~" + treeNode.name);
            };
            function zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {   
            } 
    </script>
</head>
<body>
    <form id="form1" runat="server">
   <div class="content_wrap" style="float:left;width:300px;">
    <div class="zTreeDemoBackground left">
        <ul id="treeDemo" class="ztree"></ul>
    </div>
    </div>
    </form>
</body>

WebData.aspx页面代码(用来处理数据的页面,有些地方写的比较简单...不是那么严谨)

 public partial class WebData : System.Web.UI.Page
    {
        string strConn = @"Data Source=ANDY-PC\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True";
        protected void Page_Load(object sender, EventArgs e)
        {
            #region
            try
            {
                string ajaxMethod = Request["ajaxMethod"].ToString();//取得前台ajax请求的方法名称
                System.Reflection.MethodInfo method = this.GetType().GetMethod(ajaxMethod);
                if (method != null)
                {
                    method.Invoke(this, new object[] { });//通过方法名称指向对应的方法
                }
            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                Response.End();
            }
            #endregion

        }
        /// <summary>
        /// 异步加载当前节点的子节点
        /// </summary>
        public void AnsyData()   
        {
            List<object> lsNode = new List<object>();
           try
            {            
                 int id = int.Parse(Request.Params["id"]);
                 using (SqlConnection conn = new SqlConnection(strConn))
                 {
                    string sql = "select * from OrginTree where OrgParent=" + id + "";
                    DataTable table = new DataTable();
                    SqlDataAdapter dt = new SqlDataAdapter(sql, conn);
                    dt.Fill(table);
                    lsNode = getList(table);
                    Response.Write(JsonConvert.SerializeObject(lsNode));
                 }
            }
            catch (Exception)
            {
        
                throw;
            }
        }
        /// <summary>
        /// 判断当前节点是否还有子节点
        /// </summary>
        /// <param name="ParentId">父节点Id</param>
        /// <returns>bool类型</returns>
        public bool isParentTrue(int ParentId)  
        {
            try
            {
                using (SqlConnection conn = new SqlConnection(strConn))
                {
                    conn.Open();
                    string sql = "select * from OrginTree where OrgParent ="+ParentId+"";
                    DataTable table = new DataTable();
                    SqlDataAdapter dt = new SqlDataAdapter(sql, conn);
                    dt.Fill(table);
                    return table.Rows.Count >=1 ? true :false;
                }
            }
            catch (Exception)
            {
                
                throw;
            }
        }
        /// <summary>
        /// 初始化第一次节点加载
        /// </summary>
        public void FirstAnsyData()
        {
            try
            {
                TableEnjson tbEnjson = new TableEnjson();
                List<object> lsNode = new List<object>();
                using (SqlConnection conn = new SqlConnection(strConn))
                {
                    conn.Open();
                    string sql = "select * from OrginTree where OrgParent is null";
                    DataTable table = new DataTable();
                    SqlDataAdapter dt = new SqlDataAdapter(sql, conn);
                    dt.Fill(table);
                    lsNode = getList(table);
                    Response.Write(JsonConvert.SerializeObject(lsNode));//用到了Newtonsoft.dll 转化成Json格式
                }
            }
            catch (Exception)
            {

                throw;
            }
          
        }
        /// <summary>
        /// 把数据形式转换成zTree的json数据格式
        /// </summary>
        /// <param name="table"></param>
        /// <returns></returns>
        public List<object> getList(DataTable table)
        {
            try
            {
                List<object> lsNode = new List<object>();
                bool isParent = true;
                foreach (DataRow row in table.Rows)
                {
                    var ParentId = string.IsNullOrEmpty(row["OrgParent"].ToString()) ? 0 : row["OrgParent"];
                    if (isParentTrue(int.Parse(row["OrgId"].ToString())))
                        isParent = true;
                    else
                        isParent = false;
                    var zTreeData = new
                    {
                        id = row["OrgId"],
                        pId = ParentId,
                        name = row["OrgName"],
                        isParent = isParent
                    };
                    lsNode.Add(zTreeData);
                }
                return lsNode;
            }
            catch (Exception)
            {
                
                throw;
            }
        }
    }

 数据库的格式

CREATE TABLE OrginTree
(
    OrgId INT PRIMARY KEY IDENTITY(1,1),
    OrgName NVARCHAR(30), //节点的名称
    ORgParent INT         //父节点的Id
)