码迷,mamicode.com
首页 > Web开发 > 详细

使用 ZTree.js 对树的操作

时间:2014-11-07 17:06:59      阅读:267      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   io   color   ar   os   使用   

1:引用ZTree.js 和css文件

2:前台代码:

<pre name="code" class="javascript"><script type="text/javascript">
        var zNodes;
        $(document).ready(function() {
            //获取app下拉列表的值
            AppChages();
            GetCodeById(-1, -1, '');
            //增加父节点
            AddParentId();
            //form表单提交
            SubmitForm();
        });

        //获取app下拉列表的值
        function AppChages() {
            $("#apps").change(function() {
                $("#txtParentNodeName").html("");
                EmptyText();
                if ($(this).val() == "") {
                    zNodes = "";
                    BindNodes();
                } else {
                    Search();
                }
            });
        }

        //form表单提交
        function SubmitForm() {
            $(document).on("submit", "#editForm", function() {
                if ($("#editForm").valid()) {
                    PostData();
                }
                return false;
            });
        }

        //数据提交
        function PostData() {
            if (!CheckAppKey()) return;
            $.post("@Url.Action("Edit")", $("#editForm").serialize(), function(data) {
                if (data.IsError == false) {
                    Search();
                    EmptyText();
                    $("#divEdit").css("display", "none");
                    alert("操作成功!");
                } else {
                    alert("操作失败!");
                }
            }, "json");
        }

        //添加、编辑、删除节点方法
        function OperationTree(id, pid, name, prName, action) {
            EmptyText();
            pid = pid == null ? 0 : pid;
            if (action != "del") {
                if (!CheckAppKey()) return;
            }
            if (action == "add") {
                $("#divEdit").css("display", "");
                $("#ParentId").val(id);
                $("#AppKey").val($("#apps").val());
                $("#txtParentNodeName").html(name + "/增加");
            } else if (action == "edit") {
                GetCodeById(id, pid, name);
            } else {
                $("#divEdit").css("display", "none");
                Delete(id, pid, name, $("#apps").val());
            }
            return;
        }

        //增加父节点
        function AddParentId() {
            $("#addParent").click(function() {
                if (!CheckAppKey()) return;
                $("#divEdit").css("display", "");
                EmptyText();
                $("#ParentId").val(0);
                $("#AppKey").val($("#apps").val());
                $("#txtParentNodeName").html("增加父节点");
            });
        }

        //删除节点
        function Delete(id, pid, name,appkey) {
            var conit;
            if (pid == 0) {
                conit = confirm("确定要删除\"" + name + "\"及其子菜单?");
            } else {
                conit = confirm("确定要删除\"" + name + "\"?");
            }
            if (conit) {
                var postdata = { id: id, pid: pid, appkey: appkey };
                $.post('@Url.Action("Delete", "Privilege")', postdata, function(data) {
                    if (data != null) {
                        Search();
                        if (data.IsError == true) {
                            alert("删除失败!");
                        } else {
                            alert("删除成功!");
                        }
                    }
                }, "json");
            }
            return false;
        }

        //通过主父ID和子ID查询出code值和说明字段的值
        function GetCodeById(id, pid, name) {
            var postdata = { id: id, pid: pid };
            $.post('@Url.Action("Index", "Privilege")', postdata, function(data) {
                $('#paging').html(data);
                if (name != "") {
                    $("#txtParentNodeName").html(name + "/更新");
                    $("#divEdit").css("display", "");
                }
            });
        }

        //初始化加载数据
        function Search() {
            var datalist = {};
            datalist.AppKey = $("#apps").val();
            datalist.r = Math.random();

            $.get('@Url.Action("Search", "Privilege")', datalist, function(data) {
                zNodes = eval(data);
                BindNodes();
            }, "json");
        }

//检查是否选择应用下拉列表
        function CheckAppKey() {
            var key = $("#apps").val();
            if (key == null || key == "") {
                alert("请选择应用");
                return false;
            }
            return true;
        }

//清空文本框值
        function EmptyText() {
            $("#Id").val("");
            $("#ParentId").val("");
            $("#AppKey").val("");
            $("#Name").val("");
            $("#Code").val("");
            $("#Description").val("");
            $("#txtParentNodeName").html("");
        }

//重置文本框
        function ResetText() {
            $("#Name").val("");
            $("#Code").val("");
            $("#Description").val("");
        }

        function BindNodes() {
            if (zNodes.length > 0) {
                $("#zanwushuju").hide();
                $.fn.zTree.init($("#treeDemo"), setting, zNodes);
            } else {
                $("#zanwushuju").show();
                $.fn.zTree.init($("#treeDemo"), setting, null);
            }
        }

        function setFontCss(treeId, treeNode) {
            return treeNode.status == "0" ? { color: "gray","text-decoration":"line-through"} : {};
        }

        var setting = {
            view: {
                addHoverDom: addHoverDom,
                removeHoverDom: removeHoverDom,
                autoCancelSelected: false,
                showIcon: false,
                nameIsHTML: true,
                fontCss: setFontCss
            },
            edit: {
                enable: true,
                showRemoveBtn: false,
                showRenameBtn: false
            },
            data: {
                simpleData: {
                    enable: true
                }
            },
            callback: {
            
            }
        };
        var newCount = 1;

        function addHoverDom(treeId, treeNode) {
            var sObj = $("#" + treeNode.tId + "_span");
            if (treeNode.editNameFlag || $("#addBtn_" + treeNode.id).length > 0) return;
            var addStr = "<span class='btncj addcj' id='addBtn_" + treeNode.id
                + "' title='添加' onfocus='this.blur();'></span>" + "<span class='btncj editcj' id='editBtn_" + treeNode.id
                + "' title='编辑' onfocus='this.blur();'></span>" + "<span class='btncj editdele' id='editBtn_delet" + treeNode.id
                + "' title='删除' onfocus='this.blur();'></span>";
            sObj.after(addStr);

            var parentNodeName = "";
            //添加事件
            var addbtn = $("#addBtn_" + treeNode.id);
            if (addbtn)
                addbtn.bind("click", function() {
                    OperationTree(treeNode.id, treeNode.pId, treeNode.name, parentNodeName, "add");
                    return false;
                });
            //编辑事件
            var editbtn = $("#editBtn_" + treeNode.id);
            if (editbtn)
                editbtn.bind("click", function() {
                    var zTree = $.fn.zTree.getZTreeObj("treeDemo");
                    if (treeNode) {
                        OperationTree(treeNode.id, treeNode.pId, treeNode.name, parentNodeName, "edit");
                    } else {
                        alert("叶子节点被锁定,无法增加子节点");
                    }
                    return false;
                });
            //删除事件
            var delbtn = $("#editBtn_delet" + treeNode.id);
            if (delbtn)
                delbtn.bind("click", function() {
                    var zTree = $.fn.zTree.getZTreeObj("treeDemo");
                    if (treeNode) {
                        OperationTree(treeNode.id, treeNode.pId, treeNode.name, parentNodeName, "del");
                    } else {
                        alert("叶子节点被锁定");
                    }
                    return false;
                });
        };

        function removeHoverDom(treeId, treeNode) {
            $("#addBtn_" + treeNode.id).unbind().remove();
            $("#editBtn_" + treeNode.id).unbind().remove();
            $('#editBtn_delet' + treeNode.id).unbind().remove();
        };
    </script>



       
        <div  style="padding-left: 0">
                            @Html.DropDownList("apps", ViewBag.Applications as SelectList, new { @class = "form-control input-sm" })
                        </div>
          <div class="panel-tool">
                    <button id="addParent" type="button" class="btn btn-primary btn-radius">增加父节点</button>
                </div>
           <div class="panel-body">
                    <p id="zanwushuju" class="text-center">暂无数据</p>
                    <div class="zTreeDemoBackground">
                        <ul id="treeDemo" class="ztree"></ul>
                    </div>
                </div>

后台代码:

      /// <summary>
        /// 初始化视图
        /// </summary>
        /// <returns></returns>
        public ActionResult Index(int? id, int? pid)
        {
            if (Request.IsAjaxRequest())
            {
                if (id.HasValue && pid.HasValue)
                {
                    var model = _privilegeBo.GetPrivilege(id.Value, pid.Value);
                    return PartialView("_PrivilegeTreeManager", model);
                }
            }
            InitPrivilegePageData();

            return View();
        }

        /// <summary>
        /// 初始化页面数据
        /// </summary>
        private void InitPrivilegePageData()
        {
            using (var client = new ServiceProxy<IApplicationService>())
            {
                var applications = client.Channel.GetApplicationListByAppType(AppType.管理应用);
                ViewBag.Applications = applications.ApplicationList.ToSelectList("AppName", "AppKey", "请选择");
            }
        }

        /// <summary>
        /// 通过应用key获取权限列表
        /// </summary>
        /// <param name="appKey">app key 值</param>
        /// <returns>搜索结果</returns>
        public JsonResult Search(string appKey)
        {
            if (string.IsNullOrWhiteSpace(appKey)) return Json(null, JsonRequestBehavior.AllowGet);

            var list = _privilegeBo.GetPrivilegeList(appKey);

            if (null == list) return Json(null, JsonRequestBehavior.AllowGet);

            var nodeList = list.Select(model => new ZTreeNode()
            {
                id = model.Id,
                pId = model.ParentId,
                name = model.Name,
                open = true,
                status = model.Status
            }).ToList();

            return Json(nodeList, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 添加或更新实体
        /// </summary>
        /// <param name="model">实体数据</param>
        /// <returns>是否更新或者添加成功</returns>
        public JsonResult Edit(MsPrivilege model)
        {
            var result = new Result { IsError = true };
            try
            {
                if (model.Id == 0 || model.Id == -1)
                {
                    _privilegeBo.Insert(model);
                }
                else
                {
                    var modelOld = _privilegeBo.GetPrivilege(model.Id, model.ParentId);
                    UpdateModel(modelOld);
                    _privilegeBo.Update(modelOld);
                }
                result.IsError = false;
            }
            catch (Exception ex)
            {
                result.ErrMsg = ex.Message;
            }
            return Json(result);
        }

        /// <summary>
        /// 通过条件删除数据
        /// </summary>
        /// <param name="id">节点ID</param>
        /// <param name="pid">父节点ID</param>
        /// <param name="appkey">appkey</param>
        /// <returns>json数据,是否删除成功</returns>
        public JsonResult Delete(int? id, int? pid, string appkey)
        {
            var result = new Result { IsError = true };

            if (!id.HasValue || !pid.HasValue) return Json(result);

            var flag = _privilegeBo.Delete(id.Value, pid.Value, appkey);
            result.IsError = !flag;
            return Json(result);
        }

_PrivilegeTreeManager.cshtml 页面代码:

<form id="editForm" class="form-horizontal" role="form">
    <div id="divEdit" class="col-lg-4">
        <div class="panel panel-default">
            <div class="panel-heading">
                <span class="pull-right"></span>
                <h3 class="panel-title">
                    <label id="txtParentNodeName"></label>
                </h3>
            </div>
            <div class="panel-body">
                <div class="row">
                    <div class="col-lg-3 text-right">
                        <span>名称:</span>
                    </div>
                    <div class="col-lg-9">
                        @Html.TextBoxFor(model => model.Name, new { @class = "form-control input-xs" })
                    </div>
                </div>
                <div class="row" style="margin-top: 10px">
                    <div class="col-lg-3 text-right">
                        <span>代码:</span>
                    </div>
                    <div class="col-lg-9">
                        @Html.TextBoxFor(model => model.Code, new { @class = "form-control input-xs" })
                    </div>
                </div>
                <div class="row" style="margin-top: 10px">
                    <div class="col-lg-3 text-right" style="resize: none">
                        <span>状态:</span>
                    </div>
                    <div class="col-lg-9">
                        @Html.DropDownListFor(model => model.Status, new List<SelectListItem>(){
                          new SelectListItem(){ Value = "1",Text = "启用" },
                          new SelectListItem(){ Value = "0",Text = "禁用" } }, new { @class = "form-control input-xs" })
                    </div>
                </div>
                <div class="row" style="margin-top: 10px">
                    <div class="col-lg-3 text-right" style="resize: none">
                        <span>描述:</span>
                    </div>
                    <div class="col-lg-9">
                        @Html.TextAreaFor(model => model.Description, new
                   {
                       @class = "form-control",
                       @style = "resize: none",
                       @rows = "6",
                       @onkeydown = "LimitTextArea(this)",
                       @onkeyup = "LimitTextArea(this)",
                       @onkeypress = "LimitTextArea(this)"
                   })
                    </div>
                </div>
            </div>
            <div class="panel-footer">
                <div class="clearfix">
                    <span class="pull-right">
                        @Html.HiddenFor(model => model.Id)
                        @Html.HiddenFor(model => model.ParentId)
                        @Html.HiddenFor(model => model.AppKey)
                        <button type="submit" class="btn btn-primary m10_l">保存更改</button>
                        <button type="button" class="btn btn-default" onclick="ResetText()">重置</button>
                    </span>
                </div>
            </div>
        </div>
    </div>
</form>

效果图:

bubuko.com,布布扣

使用 ZTree.js 对树的操作

标签:des   style   blog   http   io   color   ar   os   使用   

原文地址:http://blog.csdn.net/make1828/article/details/40893145

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!