ztree树应用

时间:2021-12-25 19:56:49
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ZtreeListView.ascx.cs" Inherits="SplendidCRM.Administration.CompanyOrganization.ZtreeListView" %>
<link href="ztree/demo.css" rel="stylesheet" type="text/css" />
<link href="ztree/zTreeStyle/zTreeStyle.css" rel="stylesheet" type="text/css" />
<script src="ztree/jquery-1.4.4.min.js" type="text/javascript"></script>
<script src="ztree/jquery.ztree.core-3.5.js" type="text/javascript"></script>
<script src="ztree/jquery.ztree.excheck-3.5.js" type="text/javascript"></script>
<script src="ztree/jquery.ztree.exedit.js" type="text/javascript"></script> <script type="text/javascript">
var setting = {
async: {
enable: true,
url: "ztreehandler.ashx",
autoParam: ["id", "name=n", "level=lv"],
otherParam: { "otherParam": "zTreeAsyncTest" },
dataFilter: filter
},
view: { expandSpeed: "",
addHoverDom: addHoverDom,
removeHoverDom: removeHoverDom,
selectedMulti: false
},
edit: {
enable: true
},
data: {
simpleData: {
enable: true
}
},
callback: {
beforeRemove: beforeRemove,
beforeRename: beforeRename
}
}; function filter(treeId, parentNode, childNodes) {
if (!childNodes) return null;
for (var i = , l = childNodes.length; i < l; i++) {
childNodes[i].name = childNodes[i].name.replace(/\.n/g, '.');
}
return childNodes;
}
function beforeRemove(treeId, treeNode) {
var zTree = $.fn.zTree.getZTreeObj("treeDemo");
zTree.selectNode(treeNode);
if (confirm("Confirm delete node '" + treeNode.name + "' it?")) {
$.ajax({
type: "POST",
cache: false,
async: false,
url: "ztreehandler.ashx",
data: "id=" + treeNode.id,
success: function (result) { }
});
}
else {
return false;
}
}
function beforeRename(treeId, treeNode, newName) {
if (newName.length == ) {
alert("Node name can not be empty.");
return false;
} $.ajax({
type: "POST",
cache: false,
async: false,
url: "ztreehandler.ashx",
data: "id=" + treeNode.id + "&lv=" + newName + "",
success: function (result) { }
}); return true;
} var newCount = ;
function addHoverDom(treeId, treeNode) {
var sObj = $("#" + treeNode.tId + "_span");
if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > ) return;
var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
+ "' title='add node' onfocus='this.blur();'></span>";
sObj.after(addStr);
var btn = $("#addBtn_" + treeNode.tId);
if (btn) btn.bind("click", function () {
var zTree = $.fn.zTree.getZTreeObj("treeDemo");
var newid = newGuid();
var treeName = "newNode " + (addCount++);
var level = parseInt(treeNode.level) + ;
var parentid = treeNode.id; var newNode = { id: newid, pId: parentid, name: treeName };
zTree.addNodes(treeNode, newNode); var childNodes = zTree.transformToArray(treeNode);
var nodes;
for (i = ; i < childNodes.length; i++) {
if (i == childNodes.length - ) {
nodes = childNodes[i].tId;
}
} $("#" + nodes + "_a").click();
$("#" + nodes + "_edit").click(); $.ajax({
type: "POST",
cache: false,
async: false,
url: "ztreehandler.ashx",
data: "id=" + newid + "&lv=" + treeName + "&n=" + level + "&fid=" + parentid + "",
success: function (result) { }
}); return false;
});
};
function removeHoverDom(treeId, treeNode) {
$("#addBtn_" + treeNode.tId).unbind().remove();
}; var addCount = ;
function addTreeNode() {
var treeName="newNode " + (addCount++);
var newid=newGuid();
var newNode = { id:newid,name: treeName };
var zTree = $.fn.zTree.getZTreeObj("treeDemo");
zTree.addNodes(null, newNode); //获取根节点的集合
var node = zTree.getNodesByFilter(function (node) { return node.level == })
var nodes;
for (i = ; i < node.length; i++) {
if (i == node.length - ) {
nodes = node[i].tId;
}
}
$("#" + nodes + "_a").click();
$("#" + nodes + "_edit").click(); $.ajax({
type: "POST",
cache: false,
async: false,
url: "ztreehandler.ashx",
data: "id=" + newid + "&lv=" + treeName + "&n=1",
success: function (result) { }
});
} function refreshTreeNode() {
$.fn.zTree.init($("#treeDemo"), setting);
} function newGuid() {
var guid = "";
for (var i = ; i <= ; i++) {
var n = Math.floor(Math.random() * 16.0).toString();
guid += n;
if ((i == ) || (i == ) || (i == ) || (i == ))
guid += "-";
}
return guid;
} $(document).ready(function () {
$.fn.zTree.init($("#treeDemo"), setting);
});
</script>
<style type="text/css">
.ztree li span.button.add {margin-left:2px; margin-right: -1px; background-position:-144px ; vertical-align:top; *vertical-align:middle}
</style> <input type="button" value="Add" id="Add" onclick="addTreeNode();"/>
<input type="button" value="Refresh" id="Refresh" onclick="refreshTreeNode();"/>
<div class="content_wrap">
<div class="zTreeDemoBackground left">
<ul id="treeDemo" class="ztree"></ul>
</div>
<div class="right"> </div>
</div>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using Newtonsoft.Json;
using System.Diagnostics;
using SplendidCRM.TGSAP; namespace SplendidCRM.Administration.CompanyOrganization
{
/// <summary>
/// Summary description for ztreehandler
/// </summary>
public class ztreehandler : IHttpHandler
{ public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain"; string pId = context.Request["id"] ?? "";
string pName = context.Request["lv"] ?? "";
string pLevel = context.Request["n"] ?? "";
string pCheck = context.Request["chk"] ?? "";
string fId = context.Request["fid"] ?? ""; StringBuilder sb = new StringBuilder();
if (pName != "")
{
Guid pID = Guid.Empty;
Guid gID = Guid.Empty; DbProviderFactory dbf = DbProviderFactories.GetFactory();
using (IDbConnection con = dbf.CreateConnection())
{
con.Open();
using (IDbTransaction trn = con.BeginTransaction())
{
try
{
if (pId != "")
{
if (fId != "")
{
gID = Guid.Parse(fId);
} pID = Guid.Parse(pId); if (pLevel != "")
{
if (pLevel == "")
{
APSqlProcs.spCOMPANYORGANIZATION_Update(ref pID, pName, Guid.Empty, "", trn);
}
else
{
APSqlProcs.spCOMPANYORGANIZATION_Update(ref pID, pName, gID, pLevel, trn);
}
}
else
{
APSqlProcs.spCOMPANYORGANIZATION_Update(ref pID, pName, Guid.Empty, "", trn);
}
}
trn.Commit();
}
catch (Exception ex)
{
trn.Rollback();
SplendidError.SystemError(new StackTrace(true).GetFrame(), ex);
return;
}
}
} }
else
{
if (pId != "")
{
APSqlProcs.spCOMPANYORGANIZATION_Delete(Guid.Parse(pId));
}
else
{
bingTree(sb);
}
}
context.Response.Write(sb.ToString());
} public void bingTree(StringBuilder sb)
{
DbProviderFactory dbf = DbProviderFactories.GetFactory();
using (IDbConnection con = dbf.CreateConnection())
{
string sSQL;
sSQL = "select * " + ControlChars.CrLf
+ " from COMPANYORGANIZATION" + ControlChars.CrLf
+ " where 1 = 1 AND DELETED=0 ORDER BY DATE_ENTERED ASC" + ControlChars.CrLf;
using (IDbCommand cmd = con.CreateCommand())
{
cmd.CommandText = sSQL;
using (DbDataAdapter da = dbf.CreateDataAdapter())
{
((IDbDataAdapter)da).SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
da.Fill(dt);
if (dt.Rows.Count > )
{
sb.Append(getList(dt));
}
}
}
}
}
} /// <summary>
/// 把数据形式转换成zTree的json数据格式
/// </summary>
/// <param name="table"></param>
/// <returns></returns>
public string getList(DataTable table)
{
try
{
List<object> lsNode = new List<object>();
bool isParent = true;
foreach (DataRow row in table.Rows)
{
var ParentId = string.IsNullOrEmpty(row["PARENTID"].ToString()) ? : row["PARENTID"];
if (isParentTrue(Guid.Parse(row["ID"].ToString())))
isParent = true;
else
isParent = false;
var zTreeData = new
{
id = row["ID"],
pId = ParentId,
name = row["NAME"],
isParent = isParent
};
lsNode.Add(zTreeData);
}
return JsonConvert.SerializeObject(lsNode);
}
catch (Exception)
{ throw;
}
} /// <summary>
/// 判断当前节点是否还有子节点
/// </summary>
/// <param name="ParentId">父节点Id</param>
/// <returns>bool类型</returns>
public bool isParentTrue(Guid ParentId)
{
try
{
DbProviderFactory dbf = DbProviderFactories.GetFactory();
using (IDbConnection con = dbf.CreateConnection())
{
string sSQL;
sSQL = "select * " + ControlChars.CrLf
+ " from COMPANYORGANIZATION" + ControlChars.CrLf
+ " where PARENTID='" + ParentId.ToString() + "' AND DELETED=0";
using (IDbCommand cmd = con.CreateCommand())
{
cmd.CommandText = sSQL;
using (DbDataAdapter da = dbf.CreateDataAdapter())
{
((IDbDataAdapter)da).SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
da.Fill(dt);
return dt.Rows.Count >= ? true : false;
}
}
}
} }
catch (Exception)
{ throw;
}
} public bool IsReusable
{
get
{
return false;
}
}
}
}
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[COMPANYORGANIZATION]') AND type IN (N'U'))
DROP TABLE [dbo].[COMPANYORGANIZATION]
GO CREATE TABLE COMPANYORGANIZATION
(
ID UNIQUEIDENTIFIER PRIMARY KEY,
DELETED BIT DEFAULT() NOT NULL,
CREATED_BY UNIQUEIDENTIFIER NULL,
DATE_ENTERED DATETIME DEFAULT(GETDATE()) NOT NULL,
MODIFIED_USER_ID UNIQUEIDENTIFIER NULL,
DATE_MODIFIED DATETIME DEFAULT(GETDATE()) NOT NULL,
NAME NVARCHAR() NULL,
PARENTID UNIQUEIDENTIFIER NULL,
LEVEL NVARCHAR() NULL
)
if exists (select * from sysobjects where id = object_id('dbo.spCOMPANYORGANIZATION_Update') AND OBJECTPROPERTY(id, N'IsProcedure') = )
Drop Procedure [dbo].[spCOMPANYORGANIZATION_Update];
GO Create Procedure [dbo].[spCOMPANYORGANIZATION_Update]
(
@ID uniqueidentifier output,
@MODIFIED_USER_ID uniqueidentifier = NULL,
@NAME nvarchar() = NULL,
@PARENTID uniqueidentifier = NULL,
@LEVEL nvarchar() = NULL
)
AS if not exists(select * from COMPANYORGANIZATION where ID = @ID) begin -- then
IF @LEVEL<>'' AND @LEVEL IS NOT NULL
BEGIN
insert
into [COMPANYORGANIZATION]
(
[ID],
[CREATED_BY],
[MODIFIED_USER_ID],
[NAME],
[PARENTID],
[LEVEL]
)
values
(
@ID,
@MODIFIED_USER_ID,
@MODIFIED_USER_ID,
@NAME,
@PARENTID,
@LEVEL
)
END
ELSE
BEGIN
if dbo.fnIsEmptyGuid(@ID) = begin -- then
set @ID = newid();
end -- if; insert
into [COMPANYORGANIZATION]
(
[ID],
[CREATED_BY],
[MODIFIED_USER_ID],
[NAME],
[PARENTID],
[LEVEL]
)
values
(
@ID,
@MODIFIED_USER_ID,
@MODIFIED_USER_ID,
@NAME,
@PARENTID,
@LEVEL
)
END
end else BEGIN
update [COMPANYORGANIZATION]
set
[MODIFIED_USER_ID] = @MODIFIED_USER_ID,
[DATE_MODIFIED] = getdate(),
[NAME] = @NAME
where
[ID] = @ID
end -- if; GO Grant Execute on dbo.spCOMPANYORGANIZATION_Update to public;
GO
---------------------------------------------------------------------------------------------------- if exists (select * from sysobjects where id = object_id('dbo.spCOMPANYORGANIZATION_Delete') AND OBJECTPROPERTY(id, N'IsProcedure') = )
Drop Procedure [dbo].[spCOMPANYORGANIZATION_Delete];
GO Create Procedure [dbo].[spCOMPANYORGANIZATION_Delete]
( @ID uniqueidentifier
, @MODIFIED_USER_ID uniqueidentifier
)
as
begin
set nocount on update [COMPANYORGANIZATION]
set DELETED =
, DATE_MODIFIED = getdate()
, MODIFIED_USER_ID = @MODIFIED_USER_ID
where ID = @ID
and DELETED = ;
end
GO Grant Execute on dbo.spCOMPANYORGANIZATION_Delete to public;
GO
----------------------------------------------------------------------------------------------------