Jquery zTree結合Asp.net實現異步加載數據

zTree結合Asp.net實現異步加載數據 實現簡單操做javascript

zTree 下載 api 訪問 :http://www.ztree.me/v3/main.phpphp

例子中用到json數據轉化 newtonsoft 地址 : http://json.codeplex.com/css

很少說,代碼以下 :html

aspx 頁面 :java

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="CFBuilder.WebForm2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link href="Styles/zTreeStyle/zTreeStyle.css" rel="stylesheet" type="text/css" />
    <link href="Styles/demo.css" rel="stylesheet" type="text/css" />
    <script src="Scripts/jquery-1.4.4.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery.ztree.core-3.5.min.js" type="text/javascript"></script>
       <script type="text/javascript">
            var zNodes;
             var zTree;
            //setting異步加載的設置
            var setting = {
                async: {
                enable:true, //表示異步加載生效
                url: "/AjaxService/WebData.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 () {
                Inint();
                $.fn.zTree.init($("#treeDemo"), setting, zNodes);
           });
            //初始化加載節點
            function Inint(){
                $.ajax({
                    url: '/AjaxService/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) {
                var 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" >
    <div class="zTreeDemoBackground left">
        <ul id="treeDemo" class="ztree"></ul>
    </div>
    </div>
    </form>
</body>
</html>

 

WebData.aspx頁面代碼 異步提交 交互頁面 :jquery

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using System.Data.SqlClient;
using System.Data;

namespace CFBuilder
{
    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;
            }
        }
    }

 

 數據庫的格式ajax

CREATE TABLE OrginTree
(
    OrgId INT PRIMARY KEY IDENTITY(1,1),
    OrgName NVARCHAR(30), //節點的名稱
    ORgParent INT         //父節點的Id
)
sql

相關文章
相關標籤/搜索