zTree结合Asp.net实现异步加载数据 实现简单操作
zTree 下载 api 访问 :http://www.ztree.me/v3/main.php
例子中用到json数据转化 newtonsoft 地址 : http://json.codeplex.com/
不多说,代码如下 :
aspx 页面 :
<%@ 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页面代码 异步提交 交互页面 :
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;
}
}
}
数据库的格式
CREATE TABLE OrginTree
(
OrgId INT PRIMARY KEY IDENTITY(1,1),
OrgName NVARCHAR(30), //节点的名称
ORgParent INT //父节点的Id
)