使用Jquery+EasyUI 进行框架项目开发案例讲解之五 模块(菜单)管理源码分享

在上四篇文章

  《使用Jquery+EasyUI进行框架项目开发案例讲解之一—员工管理源码分享》

  《使用Jquery+EasyUI 进行框架项目开发案例讲解之二—用户管理源码分享》

  《使用Jquery+EasyUI 进行框架项目开发案例讲解之三—角色管理源码分享》

  《使用Jquery+EasyUI 进行框架项目开发案例讲解之三—组织机构源码分享》
 
我们分享了使用Jquery EasyUI来进行ASP.NET项目的开发的相关方法,每一个模块都有其共用性,细细理解与掌握,我相信使用EasyUI进行开发还是相当方便的,每篇文章,我们力求通俗易懂。

  接下来我分享“模块(菜单)”模块主要的核心代码,“模块(菜单)”管理模块同样使用了EasyUI的TreeGrid控件,对于EasyUI的TreeGrid控件的具体使用方法可以参见上一篇 《使用Jquery+EasyUI 进行框架项目开发案例讲解之三—组织机构源码分享》的说明,或看相关的Easy UI的帮助文件,同时,我们可以看一下如何做模块图标的选择界面,模块(菜单)主界面如下图所示:  

这里写图片描述

一、“模块(菜单)”管理主界面UI的ASPX代码如下:

<%@ Page Language="C#" MasterPageFile="~/Site.Master"  AutoEventWireup="true" CodeBehind="ModuleAdmin.aspx.cs" Inherits="RDIFramework.WebApp.Modules.ModuleAdmin" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">     
     <div id="toolbar">
        <%=base.BuildToolBarButtons()%>
    </div>
    <table id="navGrid"></table>

    <script type="text/javascript" src="../Scripts/Linqjs/linq.min.js"></script>
    <script type="text/javascript" src="../Scripts/Linqjs/linq.jquery.js"></script>
    <script type="text/javascript" src="../Scripts/Business/ModuleAdmin.js?v=5"></script>

</asp:Content>

二:绑定当前登录用户所拥有的功能按钮列表代码如下:

private bool permissionUserModulePermission = false;
        private bool permissionRoleModulePermission = false;
        private bool permissionOrganizeModulePermission = false;
        private bool permissionModuleConfig = false;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                this.GetPermission();
            }
        }

        /// <summary>
        /// 获得页面的权限
        /// </summary>
        private void GetPermission()
        {
            this.permissionAdd = this.IsAuthorized("ModuleManagement.Add");
            this.permissionEdit = this.IsAuthorized("ModuleManagement.Edit");
            this.permissionDelete = this.IsAuthorized("ModuleManagement.Delete");
            this.permissionExport = this.IsAuthorized("ModuleManagement.Export");
            //this.permissionAccredit = this.IsAuthorized("UserManagement.Accredit");
            this.permissionUserModulePermission = this.IsAuthorized("ModuleManagement.UserModulePermission");
            this.permissionRoleModulePermission = this.IsAuthorized("ModuleManagement.RoleModulePermission");
            this.permissionOrganizeModulePermission = this.IsAuthorized("ModuleManagement.OrganizeModulePermission") && SystemInfo.EnableOrganizePermission;
            this.permissionModuleConfig = this.IsAuthorized("ModuleManagement.ModuleConfig");
        }

        /// <summary>
        /// 加载工具栏
        /// </summary>
        /// <returns>工具栏HTML</returns>
        public override string BuildToolBarButtons()
        {
            StringBuilder sb = new StringBuilder();
            string linkbtn_template = "<a id=\"a_{0}\" class=\"easyui-linkbutton\" style=\"float:left\"  plain=\"true\" href=\"javascript:;\" icon=\"{1}\"  {2} title=\"{3}\">{4}</a>";
            sb.Append("<a id=\"a_refresh\" class=\"easyui-linkbutton\" style=\"float:left\"  plain=\"true\" href=\"javascript:;\" icon=\"icon-reload\"  title=\"重新加载\">刷新</a> ");
            sb.Append("<div class='datagrid-btn-separator'></div> ");
            sb.Append(string.Format(linkbtn_template, "add", "icon-tab_add", permissionAdd ? "" : "disabled=\"True\"", "新增模块(菜单)", "新增"));
            sb.Append(string.Format(linkbtn_template, "edit", "icon-tab_edit", permissionEdit ? "" : "disabled=\"True\"", "修改选中的模块(菜单)", "修改"));
            sb.Append(string.Format(linkbtn_template, "delete", "icon-tab_delete", permissionDelete ? "" : "disabled=\"True\"", "删除选中的模块(菜单)", "删除"));
            sb.Append("<div class='datagrid-btn-separator'></div> ");
            //sb.Append(string.Format(linkbtn_template, "move", "icon-shape_move_forwards", permissionMove ? "" : "disabled=\"True\"", "移动选中的模块(菜单)", "移动"));
            sb.Append(string.Format(linkbtn_template, "export", "icon-tab_go", permissionExport ? "" : "disabled=\"True\"", "导出模块(菜单)数据", "导出"));
            sb.Append("<div class='datagrid-btn-separator'></div> ");
            sb.Append(string.Format(linkbtn_template, "setusermodulepermission", "icon-user_key", permissionUserModulePermission ? "" : "disabled=\"True\"", "设置用户的模块(菜单)访问权限", "用户模块权限"));
            sb.Append(string.Format(linkbtn_template, "setrolemodulepermission", "icon-group_key", permissionRoleModulePermission ? "" : "disabled=\"True\"", "设置角色的模块(菜单)访问权限", "角色模块权限"));
            sb.Append("<div class='datagrid-btn-separator'></div> ");
            sb.Append(string.Format(linkbtn_template, "moduleconfig", "icon-table_gear", permissionRoleModulePermission ? "" : "disabled=\"True\"", "设置模块的可用性", "模块配置"));
            return sb.ToString();
        }

三、绑定模块主wldmTreeGrid 的JS代码如下:

var grid = {
    databind: function (winsize) {
        navgrid = $('#navGrid').treegrid({
            toolbar: '#toolbar',
            title: '模块(菜单)列表',
            iconCls: 'icon icon-chart_organisation',
            width: winsize.width,
            height: winsize.height,
            nowrap: false,
            rownumbers: true,
            //animate: true,
            resizable: true,
            collapsible: false,
            url: actionUrl,
            idField: 'Id',
            treeField: 'FullName',
            frozenColumns: [[
                { title: '模块(菜单)名称', field: 'FullName', width: 200 },
                { title: '编码', field: 'Code', width: 130 }
            ]],
            columns: [[
                { title: 'Id', field: 'Id', hidden: true },
                { title: 'ParentId', field: 'ParentId', hidden: true },
                { title: '模块分类', field: 'Category', width: 100 },
                { title: '图标', field: 'IconCss', width: 130, hidden: true },
                { title: 'Web链接地址', field: 'NavigateUrl', width: 200 },
                { title: 'WinForm程序集', field: 'AssemblyName', width: 150 },
                { title: 'WinForm窗体', field: 'FormName', width: 200 },
                {
                    title: '公共', field: 'IsPublic', width: 50, align: 'center', formatter: function (v, d, i) {
                        return '<img src="http://images.cnblogs.com/' + (v ? "checkmark.gif" : "checknomark.gif") + '" />';
                    }
                },
                { title: '有效', field: 'Enabled', width: 50, align: 'center', formatter: imgcheckbox },               
                { title: 'AllowEdit', field: 'AllowEdit', hidden: true },
                { title: 'AllowDelete', field: 'AllowDelete', hidden: true },
                { title: '排序', field: 'SortCode', width: 80 },
                { title: '备注', field: 'Description', width: 500 }
            ]]
        });
    },
    reload: function () {
        navgrid.treegrid('reload');
    },
    selected: function () {
        return navgrid.treegrid('getSelected');
    }
};

var imgcheckbox = function (cellvalue, options, rowObject) {
    return cellvalue ? '<img src="/css/icon/ok.png" alt="正常" title="正常" />' : '<img src="/css/icon/stop.png" alt="禁用" title="禁用" />';
}

四、添加与模块(菜单)主界面  

这里写图片描述

  代码如下: 

add: function () {
        if ($(this).linkbutton('options').disabled == true) {
            return;
        }
        var addDialog = top.$.hDialog({
            href: formUrl, title: '添加模块(菜单)', iconCls: 'icon-tab_add', width: 490, height: 550,
            onLoad: function () {
                crud.bindCtrl();
                crud.bindCategory();
                var row = grid.selected();
                if (row) {
                    top.$('#txt_ParentId').combotree('setValue', row.ParentId);
                }
            },
            submit: function () {
                if (top.$('#uiform').validate().form()) {
                    //var param = createParam('add', '0');
                    var vcategory = top.$('#txt_Category').combobox('getValue');
                    var vparentid = top.$('#txt_ParentId').combobox('getValue');
                    var param = 'action=Add&vcategory=' + vcategory + '&vparentid=' + vparentid + '&' + top.$('#uiform').serialize();
                    $.ajaxjson(actionUrl, param, function (d) {
                        if (d.Success) {
                            msg.ok(d.Message);
                            addDialog.dialog('close');
                            grid.reload();
                        } else {
                            MessageOrRedirect(d);
                        }
                    });
                }
            }
        });
    },
    edit: function () {
        if ($(this).linkbutton('options').disabled == true) {
            return;
        }
        var row = grid.selected();
        if (row) {
            var editDailog = top.$.hDialog({
                href: formUrl, title: '修改模块(菜单)', iconCls: 'icon-tab_edit', width: 490, height: 550,
                onLoad: function () {
                    crud.bindCtrl(row.Id);
                    crud.bindCategory();
                    top.$('#txt_Code').val(row.Code);
                    top.$('#txt_FullName').val(row.FullName);
                    top.$('#txt_Category').combobox('setValue', row.Category);
                    top.$('#txt_ParentId').combotree('setValue', row.ParentId);
                    top.$('#txt_NavigateUrl').val(row.NavigateUrl);
                    top.$('#txt_IconCss').val(row.IconCss);
                    //top.$('#smallIcon').attr('class', "icon " + row.IconCss);
                    top.$('#smallIcon').attr('class', row.IconCss);
                    top.$('#txt_AssemblyName').val(row.AssemblyName);
                    top.$('#txt_FormName').val(row.FormName);
                    top.$('#chk_Enabled').attr('checked', row.Enabled == "1");
                    top.$('#chk_IsPublic').attr('checked', row.IsPublic == "1");
                    top.$('#chk_Expand').attr('checked', row.Expand == "1");
                    top.$('#chk_AllowEdit').attr('checked', row.AllowEdit == "1");
                    top.$('#chk_AllowDelete').attr('checked', row.AllowDelete == "1");
                    top.$('#txt_Description').val(row.Description);
                    top.$('#txt_IconUrl').val(row.IconUrl);
                },
                submit: function () {
                    if (top.$('#uiform').validate().form()) {
                        //保存时判断当前节点所选的父节点,不能为当前节点的子节点,这样就乱套了....
                        var treeParentId = top.$('#txt_ParentId').combotree('tree'); // 得到树对象
                        var node = treeParentId.tree('getSelected');
                        if (node) {
                            var nodeParentId = treeParentId.tree('find', row.Id);
                            var children = treeParentId.tree('getChildren', nodeParentId.target);
                            var nodeIds = '';
                            var isFind = 'false';
                            for (var index = 0; index < children.length; index++) {
                                if (children[index].id == node.id) {
                                    isFind = 'true';
                                    break;
                                }
                            }

                            if (isFind == 'true') {
                                top.$.messager.alert('温馨提示', '请选择父节点元素!', 'warning');
                                return;
                            }
                        }

                        var vcategory = top.$('#txt_Category').combobox('getValue');
                        var vparentid = top.$('#txt_ParentId').combobox('getValue');
                        var query = 'action=Edit&vcategory=' + vcategory + '&vparentid=' + vparentid + '&KeyId=' + row.Id + '&' + top.$('#uiform').serialize();
                        $.ajaxjson(actionUrl, query, function (d) {
                            if (d.Success) {
                                msg.ok(d.Message);
                                editDailog.dialog('close');
                                grid.reload();
                            } else {
                                MessageOrRedirect(d);
                            }
                        });
                    }
                }
            });


        } else {
            msg.warning('请选择要修改菜单!');
            return false;
        }
        return false;
    }

  在模块(菜单)编辑与新增界面上,我们可以设置模块的图标,设置模块图标如下图所示:
这里写图片描述
  这个是如何实现的呢?

  首先准备图标的基页面,截取部分格式如下,保存为一个html文件,如:iconlist.htm: 

<ul id="iconlist" style="margin:0px;padding:0px; list-style-type:none;">
<li title="/css/icon/accept.png"><span class="icon icon-accept"> </span></li>
<li title="/css/icon/add.png"><span class="icon icon-add"> </span></li>
<li title="/css/icon/advancedsettings.png"><span class="icon icon-advancedsettings"> </span></li>
<li title="/css/icon/advancedsettings2.png"><span class="icon icon-advancedsettings2"> </span></li>
<li title="/css/icon/anchor.png"><span class="icon icon-anchor"> </span></li>
<li title="/css/icon/application.png"><span class="icon icon-application"> </span></li>
<li title="/css/icon/application_delete.png"><span class="icon icon-application_delete"> </span></li>
<li title="/css/icon/application_double.png"><span class="icon icon-application_double"> </span></li>
<li title="/css/icon/application_edit.png"><span class="icon icon-application_edit"> </span></li>
<li title="/css/icon/application_error.png"><span class="icon icon-application_error"> </span></li>
<li title="/css/icon/application_form.png"><span class="icon icon-application_form"> </span></li>
<li title="/css/icon/application_form_add.png"><span class="icon icon-application_form_add"> </span></li>
<li title="/css/icon/application_form_delete.png"><span class="icon icon-application_form_delete"> </span></li>
<li title="/css/icon/application_form_edit.png"><span class="icon icon-application_form_edit"> </span></li>
<li title="/css/icon/application_form_magnify.png"><span class="icon icon-application_form_magnify"> </span></li>
<li title="/css/icon/application_get.png"><span class="icon icon-application_get"> </span></li>
<li title="/css/icon/application_go.png"><span class="icon icon-application_go"> </span></li>
<li title="/css/icon/application_home.png"><span class="icon icon-application_home"> </span></li>
<li title="/css/icon/application_key.png"><span class="icon icon-application_key"> </span></li>
<li title="/css/icon/application_lightning.png"><span class="icon icon-application_lightning"> </span></li>
<ul> </ul></ul>

  然后在我们的js中调用这个html做相应的处理即可了,js部分代码为:

var showIcon = function () {
    top.$('#selecticon').click(function () {
        var iconDialog = top.$.hDialog({
            iconCls: 'icon-application_view_icons',
            href: '/css/iconlist.htm?v=' + Math.random(),
            title: '选取图标', width: 800, height: 600, showBtns: false,
            onLoad: function () {
                top.$('#iconlist li').attr('style', 'float:left;border:1px solid #fff;margin:2px;width:16px;cursor:pointer').click(function () {
                    //var iconCls = top.$(this).find('span').attr('class').replace('icon ', '');
                    var iconCls = top.$(this).find('span').attr('class');
                    top.$('#txt_IconCss').val(iconCls);
                    top.$('#txt_IconUrl').val(top.$(this).attr('title'));
                    //top.$('#smallIcon').attr('class', "icon " + iconCls);
                    top.$('#smallIcon').attr('class', iconCls);

                    iconDialog.dialog('close');
                }).hover(function () {
                    top.$(this).css({ 'border': '1px solid red' });
                }, function () {
                    top.$(this).css({ 'border': '1px solid #fff' });
                });
            }
        });
    });
};

五、用户模块(菜单)权限批量设置

  用户模块(菜单)权限功能项用于设置那些用户可以访问那些模块,那些用户不能访问那些模块。用户模块(菜单)权限设置如下图用户模块(菜单)权限集中设置。左侧列出框架的所有有效用户,右侧为模块(菜单)项,选中相应的模块后保存,即可为当前选中用户授予模块的访问权限。

这里写图片描述
  js代码如下:

userModulePermissionBatchSet: function () { //用户模块(菜单)权限批量设置
        if ($(this).linkbutton('options').disabled == true) {
            return;
        }
        var userGrid;
        var curUserModuleIds = []; //当前所选用户所拥有的模块ID
        var setDialog = top.$.hDialog({
            title: '用户模块(菜单)权限批量设置',
            width: 670, height: 600, iconCls: 'icon-user_key', //cache: false,
            href: "Modules/html/PermissionBacthSetForm.htm?n=" + Math.random(),
            onLoad: function () {
                using('panel', function () {
                    top.$('#panelTarget').panel({ title: '模块(菜单)', iconCls: 'icon-org', height: $(window).height() - 3 });
                });

                userGrid = top.$('#leftnav').datagrid({
                    title: '所有用户',
                    url: 'Modules/handler/UserAdminHandler.ashx',
                    nowrap: false, //折行
                    //fit: true,
                    rownumbers: true, //行号
                    striped: true, //隔行变色
                    idField: 'Id', //主键
                    singleSelect: true, //单选
                    frozenColumns: [[]],
                    columns: [[
                        { title: '登录名', field: 'UserName', width: 120, align: 'left' },
                        { title: '用户名', field: 'RealName', width: 150, align: 'left' }
                    ]],
                    onLoadSuccess: function (data) {
                        top.$('#rightnav').tree({
                            cascadeCheck: false, //联动选中节点
                            checkbox: true,
                            lines: true,
                            url: 'Modules/handler/ModuleAdminHandler.ashx?action=GetModuleTree',
                            onSelect: function (node) {
                                top.$('#rightnav').tree('getChildren', node.target);
                            }
                        });
                        top.$('#leftnav').datagrid('selectRow', 0);
                    },
                    onSelect: function (rowIndex, rowData) {
                        curUserModuleIds = [];
                        var query = 'action=GetModuleByUserId&userid=' + rowData.Id;
                        $.ajaxtext('handler/PermissionHandler.ashx', query, function (data) {
                            var moduelTree = top.$('#rightnav');
                            moduelTree.tree('uncheckedAll');
                            if (data == '' || data.toString() == '[object XMLDocument]') {
                                return;
                            }
                            curUserModuleIds = data.split(',');
                            for (var i = 0; i < curUserModuleIds.length; i++) {
                                var node = moduelTree.tree('find', curUserModuleIds[i]);
                                if (node)
                                    moduelTree.tree("check", node.target);
                            }
                        });
                    }
                });
            },
            submit: function () {
                var allSelectModuledIds = permissionMgr.getUserSelectedModule().split(',');
                var grantModuleIds = '';
                var revokeModuleIds = '';
                var flagRevoke = 0;
                var flagGrant = 0;
                while (flagRevoke < curUserModuleIds.length) {
                    if ($.inArray(curUserModuleIds[flagRevoke], allSelectModuledIds) == -1) {
                        revokeModuleIds += curUserModuleIds[flagRevoke] + ','; //得到收回的权限列表
                    }
                    ++flagRevoke;
                }

                while (flagGrant < allSelectModuledIds.length) {
                    if ($.inArray(allSelectModuledIds[flagGrant], curUserModuleIds) == -1) {
                        grantModuleIds += allSelectModuledIds[flagGrant] + ','; //得到授予的权限列表
                    }
                    ++flagGrant;
                }

                var query = 'action=SetUserModulePermission&userid=' + top.$('#leftnav').datagrid('getSelected').Id + '&grantIds=' + grantModuleIds + "&revokeIds=" + revokeModuleIds;
                $.ajaxjson('handler/PermissionHandler.ashx', query, function (d) {
                    if (d.Data > 0) {
                        msg.ok('设置成功!');
                    }
                    else {
                        alert(d.Message);
                    }
                });
            }
        });
    }

六、角色模块(菜单)权限批量设置

  角色模块(菜单)操作权限用于设置那些角色拥有那些操作(功能)权限,那些角色不拥有那些操作(功能)权限。如下图所示,左侧列出框架的所有有效角色,右侧为相应的模块(菜单),选中相应的模块(菜单)后保存,即可为当前选中角色授予相应的模块(菜单)可访问的控制。

这里写图片描述

  js部分代码如下:

roleModulePermissionBatchSet: function () { //角色模块(菜单)权限批量设置
        if ($(this).linkbutton('options').disabled == true) {
            return;
        }
        var roleGrid;
        var curRoleModuleIds = []; //当前所选角色所拥有的模块ID
        var setDialog = top.$.hDialog({
            title: '角色模块(菜单)权限批量设置',
            width: 670, height: 600, iconCls: 'icon-group_key', //cache: false,
            href: "Modules/html/PermissionBacthSetForm.htm?n=" + Math.random(),
            onLoad: function () {
                using('panel', function () {
                    top.$('#panelTarget').panel({ title: '模块(菜单)', iconCls: 'icon-org', height: $(window).height() - 3 });
                });
                roleGrid = top.$('#leftnav').datagrid({
                    title: '所有角色',
                    url: 'Modules/handler/RoleAdminHandler.ashx?action=getrolelist',
                    nowrap: false, //折行
                    //fit: true,
                    rownumbers: true, //行号
                    striped: true, //隔行变色
                    idField: 'Id', //主键
                    singleSelect: true, //单选
                    frozenColumns: [[]],
                    columns: [[
                        { title: '角色编码', field: 'Code', width: 120, align: 'left' },
                        { title: '角色名称', field: 'RealName', width: 150, align: 'left' }
                    ]],
                    onLoadSuccess: function (data) {
                        top.$('#rightnav').tree({
                            cascadeCheck: false, //联动选中节点
                            checkbox: true,
                            lines: true,
                            url: 'Modules/handler/ModuleAdminHandler.ashx?action=GetModuleTree',
                            onSelect: function (node) {
                                top.$('#rightnav').tree('getChildren', node.target);
                            }
                        });
                        top.$('#leftnav').datagrid('selectRow', 0);
                    },
                    onSelect: function (rowIndex, rowData) {
                        curRoleModuleIds = [];
                        var query = 'action=GetModuleByRoleId&roleid=' + rowData.Id;
                        $.ajaxtext('handler/PermissionHandler.ashx', query, function (data) {
                            var moduelTree = top.$('#rightnav');
                            moduelTree.tree('uncheckedAll');
                            if (data == '' || data.toString() == '[object XMLDocument]') {
                                return;
                            }
                            curRoleModuleIds = data.split(',');
                            for (var i = 0; i < curRoleModuleIds.length; i++) {
                                var node = moduelTree.tree('find', curRoleModuleIds[i]);
                                if (node)
                                    moduelTree.tree("check", node.target);
                            }
                        });
                    }
                });
            },
            submit: function () {
                var allSelectModuledIds = permissionMgr.getUserSelectedModule().split(',');
                var grantModuleIds = '';
                var revokeModuleIds = '';
                var flagRevoke = 0;
                var flagGrant = 0;
                while (flagRevoke < curRoleModuleIds.length) {
                    if ($.inArray(curRoleModuleIds[flagRevoke], allSelectModuledIds) == -1) {
                        revokeModuleIds += curRoleModuleIds[flagRevoke] + ','; //得到收回的权限列表
                    }
                    ++flagRevoke;
                }

                while (flagGrant < allSelectModuledIds.length) {
                    if ($.inArray(allSelectModuledIds[flagGrant], curRoleModuleIds) == -1) {
                        grantModuleIds += allSelectModuledIds[flagGrant] + ','; //得到授予的权限列表
                    }
                    ++flagGrant;
                }
                var query = 'action=SetRoleModulePermission&roleid=' + top.$('#leftnav').datagrid('getSelected').Id + '&grantIds=' + grantModuleIds + "&revokeIds=" + revokeModuleIds;
                $.ajaxjson('handler/PermissionHandler.ashx', query, function (d) {
                    if (d.Data > 0) {
                        msg.ok('设置成功!');
                    }
                    else {
                        alert(d.Message);
                    }
                });
            }
        });
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值