一,使用前需要引入的脚本文件(可从官网下载:http://www.ztree.me/v3/main.php#_zTreeInfo)
<link href="~/Content/CSS/zTreeStyle/zTreeStyle.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/ztree/3.3/jquery.ztree.all-3.3.js"></script>
<script src="~/Scripts/ztree/3.3/jquery.ztree.core-3.3.js"></script>
<script src="~/Scripts/ztree/3.3/jquery.ztree.excheck-3.3.js"></script>
<script src="~/Scripts/ztree/3.3/jquery.ztree.exedit-3.3.js"></script>
<script src="~/Scripts/ztree/3.3/jquery.ztree.exhide-3.3.js"></script>
二、
2.1 前台html页面
<div id="treeDIV" style="float: left; margin: 5px 10px; overflow-y: auto">
<ul id="zTree" class="ztree"></ul>
<input type="hidden" id="hdZtree" />
</div>
2.2 ztree配置及代码文件
<script type="text/javascript">
$(function () {
initzTree();
});
/*项目管理的树形结构方法Begin*/
function initzTree() {
var setting4 = {
data: {
simpleData: {
enable: true,
idKey: "id",
pIdKey: "pId",
rootPId: 0
}
},
view: {
addHoverDom: addHoverDom,
removeHoverDom: removeHoverDom,
selectedMulti: false,
showIcon: true
},
check: {
enable: false
},
async: {
//异步加载
enable: true,
contentType: "application/json",
url: "/EquipmentType/AsyncGetNodes",
autoParam: ["id", "pId", "name"]
},
edit: {
drag: {
autoExpandTrigger: true,
prev: true,
inner: true,
next: true
},
enable: true,
editNameSelectAll: true,
showRemoveBtn: showRemoveBtn,
showRenameBtn: true,
removeTitle: "删除",
renameTitle: "修改",
},
callback: {
beforeRename: beforeRename,//修改失去焦点
onRename: onRename,//保存到数据库
beforeRemove: beforeRemove,//删除
onClick: onClick,
onAsyncSuccess: onAsyncSuccess,
//beforeDrag: beforeDrag,
//beforeDrop: beforeDrop,
//beforeDragOpen: beforeDragOpen,
//onDrag: onDrag,
//onDrop: onDrop,
//beforeRemove: beforeRemove,//删除
beforeClick: zTreeBeforeClick,
//onCheck: onCheck,
}
};
var zTree = $.fn.zTree.init($("#zTree"), setting4, null);
var nodes = zTree.getNodeByParam("id", 0, null);
zTree.expandNode(nodes, true, false, true);
};
//一些其他可能使用的方法
function beforeRename(treeId, treeNode, newName, isCancel) {
if (newName.length == 0) {
alert("节点名称不能为空.");
var zTree = $.fn.zTree.getZTreeObj("zTree");
setTimeout(function () { zTree.editName(treeNode) }, 10);
return false;
}
}
function removeHoverDom(treeId, treeNode) {
var aObj = $("#" + treeNode.tId + "_a");
$("#addBtn_" + treeNode.tId).unbind().remove();
$(".edit.button").attr("style", "display:none;");
$(".remove.button").attr("style", "display:none;");
$(".button.add").attr("style", "display:none;");
aObj.removeClass("curSelectedNode");
};
//重写节点的beforeClick事件
function zTreeBeforeClick(treeId, treeNode, clickFlag) {
//判断当前节点是否有noselect属性 无则允许选中,有且设置为true则return fasle表示不许选中。
if (treeNode.noselect != undefined && treeNode.noselect) {
return true;
}
return false;
}
//是否显示删除按钮
function showRemoveBtn(treeId, treeNode) {
if (treeNode.IsProject == "false") {
return false;
}
return true;
}
function onClick(e, treeId, treeNode) {
if (treeNode.IsProject == "true") {
$(".edit.button").attr("style", "display:compact;");
$(".remove.button").attr("style", "display:compact;");
ChangSelectOrEditIframe(treeNode.id,treeNode.name);
CancelHiddenBtn();
}
}
function onAsyncSuccess(event, treeId, msg) {
var zTree = $.fn.zTree.getZTreeObj("zTree");
var node = zTree.getNodeByParam("name", "@Model.TypeName", null);
try {
zTree.selectNode(node);
ChangSelectOrEditIframe(@Model.ID,treeId.name)
} catch (err) {
}
}
var newCount = 1;
//新增节点
function addHoverDom(treeId, treeNode) {
var aObj = $("#" + treeNode.tId + "_a");
var aRemove = $("#" + treeNode.tId + "_remove");
var aEdit = $("#" + treeNode.tId + "_edit");
var aAdd = $("#addBtn_" + treeNode.tId);//addBtn_zTree_8
aRemove.attr("style", "display:normal;");
aEdit.attr("style", "display:normal;");
aAdd.attr("style", "display:normal;");
aObj.addClass("curSelectedNode");
if (treeNode.IsProject == "true") {
$("#hdZtree").val(treeNode.id);
return false;
}
var sObj = $("#" + treeNode.tId + "_span");
if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0) return;
var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
+ "' title='新增' onfocus='this.blur();'></span>";
sObj.after(addStr);
var btn = $("#addBtn_" + treeNode.tId);
if (btn) btn.bind("click", function () {
var zTree = $.fn.zTree.getZTreeObj("zTree");
zTree.addNodes(treeNode, { id: (100 + newCount), pId: treeNode.id, name: "默认名称" + (newCount++) });
var id = newCount;
var name = "默认名称" + id;
$.ajax({
url: "/EquipmentType/AddEquipmentType?Pid=" + treeNode.id + "&Name=" + encodeURI(name), //后台处理程序
type: "post", //数据发送方式
async: false,
dataType: "json",
success: function (data) {
if (data == 0) {
alert("新增失败");
location.reload();
return false;
}
else {
location.reload();
return true;
}
},
error: function () {
alert("服务器没有返回数据,可能服务器忙,请重试");
}
});
return false;
});
};
//删除节点
function beforeRemove(treeId, treeNode) {
var ID = treeNode.id;
if (confirm("确认删除 节点 -- " + treeNode.name + " 吗?")) {
$.ajax({
url: "/EquipmentType/DelEquipmentByID?ID=" + ID, //后台处理程序
type: "post", //数据发送方式
async: false,
dataType: "html",
success: function (data) {
if (data == 1) {
return true;
}
else {
alert("删除失败!");
initzTree();
return false;
}
},
error: function () {
alert("服务器没有返回数据,可能服务器忙,请重试");
return false;
}
});
}
else {
return false;
}
}
//修改节点信息,保存到数据库
function onRename(e, treeId, treeNode, isCancel) {
var nodename = treeNode.name;
var ID = treeNode.id;
$.ajax({
url: "/EquipmentType/EditEquipmentTypeByID?ID=" + ID + "&Name=" + encodeURI(nodename), //后台处理程序
type: "post", //数据发送方式
async: false,
dataType: "html",
success: function (data) {
if (data == 0) {
alert("修改失败");
var zTree = $.fn.zTree.getZTreeObj("zTree");
setTimeout(function () { zTree.editName(treeNode) }, 10);
return false;
}
initzTree();
return true;
},
error: function () {
alert("服务器没有返回数据,可能服务器忙,请重试");
}
});
}
</script>
三、
3.1 后台代码(异步获取ztree节点):
public class EquipmentTypeController : Controller
{
public ActionResult AsyncGetNodes()
{
IEnumerable<ZNode> nodes = new List<ZNode>();//ZNode见下面帮助类
EquipmentType eqtModel = db.EquipmentType.Where(eqt => eqt.PID == 0).ToList().FirstOrDefault();
var pnode = new ZNode();
pnode.id = eqtModel.ID.ToString();
pnode.pId = "0";
pnode.name = eqtModel.TypeName;
pnode.open = true;
pnode.drop = true;
pnode.IsProject = "false";
pnode.icon = "../Content/css/zTreeStyle/img/diy/1_open.png";
pnode.noselect = false;
List<EquipmentType> eqtModelNode = db.EquipmentType.Where(dep => dep.PID != 0).ToList();
JavaScriptSerializer jss = new JavaScriptSerializer();
string ResultDt = jss.Serialize(eqtModelNode);
JArray ja = (JArray)JsonConvert.DeserializeObject(ResultDt);
foreach (JObject jo in ja)
{
var node = new ZNode();
int id = Convert.ToInt32(jo["ID"].ToString());
node.id = jo["ID"].ToString();
node.pId = jo["PID"].ToString();
node.name = jo["TypeName"].ToString();
node.open = true;
node.drop = true;
node.noselect = false;
if (jo["EquipmentLevel"].ToString() == "2")
{
node.IsProject = "true";
node.noselect = true;
}
else
{
node.icon = "../Content/css/zTreeStyle/img/diy/ico_close2.png";
}
(nodes as List<ZNode>).Add(node);
}
(nodes as List<ZNode>).Add(pnode);
return Json(nodes);
}
}
3.2 帮助类(ZNode)
/// <summary>
/// 树节点
/// </summary>
public class ZNode
{
public string name { get; set; }
public string id { get; set; }
public string pId { get; set; }
public string target { get; set; }
public string url { get; set; }
public string icon { get; set; }
public string iconClose { get; set; }
public string iconOpen { get; set; }
public string iconSkin { get; set; }
public Boolean @checked { get; set; }
public Boolean isParent { get; set; }
public Boolean open { get; set; }
public List<ZNode> children;
public Boolean drop { get; set; }
public string IsProject { get; set; }
public bool noselect { get; set; }
}