构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(23)-权限管理系统-角色组模块

接下来我们的目标是

  1. 角色组管理
  2. 角色组权限设置
  3. 用户管理
  4. 把角色组授权给用户
  5. 给用户分配角色组

所以最少我们还要讲多5讲才能结束这个管理系统,经过之前的样例程序,我们很熟悉这个套路了,如果你很喜欢这个系列,你可以为这种重复性的动作写一个简单的代码生成器,或者一套强大的T4模版,其实这2个我都有,而且也是刚写的,以后系统完善了,给发布出来。

是不是还可以呢,哈哈,T4我也写了一套,但毕竟还是没有winfrom来得方便。

接下来我们在之前做好的模块管理,在22讲中,添加角色组管理的记录和操作码,如图

目前我是需要添加这么多个操作码。回头就机械性的创建DAL层,BLL层,Model层,还有注入

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using App.Models;

namespace App.IDAL
{
    public interface ISysRoleRepository
    {
     
        IQueryable<SysRole> GetList(DBContainer db);
        int Create(SysRole entity);
        int Delete(string id);
        int Edit(SysRole entity);
        SysRole GetById(string id);
        bool IsExist(string id);
    }

}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using App.Models;
using App.IDAL;
using System.Data;

namespace App.DAL
{
    public class SysRoleRepository : IDisposable,ISysRoleRepository
    {

        public IQueryable<SysRole> GetList(DBContainer db)
        {
            IQueryable<SysRole> list = db.SysRole.AsQueryable();
            return list;
        }

        public int Create(SysRole entity)
        {
            using (DBContainer db = new DBContainer())
            {
                db.SysRole.AddObject(entity);
                return db.SaveChanges();
            }
        }

        public int Delete(string id)
        {
            using (DBContainer db = new DBContainer())
            {
                SysRole entity = db.SysRole.SingleOrDefault(a => a.Id == id);
                if (entity != null)
                {

                    db.SysRole.DeleteObject(entity);
                }
                return db.SaveChanges();
            }
        }

        public int Edit(SysRole entity)
        {
            using (DBContainer db = new DBContainer())
            {
                db.SysRole.Attach(entity);
                db.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
                return db.SaveChanges();
            }
        }

        public SysRole GetById(string id)
        {
            using (DBContainer db = new DBContainer())
            {
                return db.SysRole.SingleOrDefault(a => a.Id == id);
            }
        }

        public bool IsExist(string id)
        {
            using (DBContainer db = new DBContainer())
            {
                SysRole entity = GetById(id);
                if (entity != null)
                    return true;
                return false;
            }
        }

        public void Dispose()
        {

        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using App.Models;
using App.Common;
using App.Models.Sys;

namespace App.IBLL
{
    public interface ISysRoleBLL
    {
        List<SysRoleModel> GetList(ref GridPager pager, string queryStr);
        bool Create(ref ValidationErrors errors, SysRoleModel model);
        bool Delete(ref ValidationErrors errors, string id);
        bool Edit(ref ValidationErrors errors, SysRoleModel model);
        SysRoleModel GetById(string id);
        bool IsExist(string id);
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Practices.Unity;
using App.Models;
using App.Common;
using System.Transactions;
using App.Models.Sys;
using App.IBLL;
using App.IDAL;
using App.BLL.Core;

namespace App.BLL
{
    public class SysRoleBLL : BaseBLL, ISysRoleBLL
    {
        [Dependency]
        public ISysRoleRepository m_Rep { get; set; }
        public List<SysRoleModel> GetList(ref GridPager pager, string queryStr)
        {

            IQueryable<SysRole> queryData = null;
            if (!string.IsNullOrWhiteSpace(queryStr))
            {
                queryData = m_Rep.GetList(db).Where(a => a.Name.Contains(queryStr));
            }
            else
            {
                queryData = m_Rep.GetList(db);
            }
            pager.totalRows = queryData.Count();
            queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
            return CreateModelList(ref queryData);
        }
        private List<SysRoleModel> CreateModelList(ref IQueryable<SysRole> queryData)
        {
            List<SysRoleModel> modelList = new List<SysRoleModel>();
            foreach (var r in queryData)
            {
                modelList.Add(new SysRoleModel()
                {
                    Id = r.Id,
                    Name = r.Name,
                    Description = r.Description,
                    CreateTime = r.CreateTime,
                    CreatePerson = r.CreatePerson,
                    UserName = ""
                });
            }
            return modelList;
        }

        public bool Create(ref ValidationErrors errors, SysRoleModel model)
        {
            try
            {
                SysRole entity = m_Rep.GetById(model.Id);
                if (entity != null)
                {
                    errors.Add(Suggestion.PrimaryRepeat);
                    return false;
                }
                entity = new SysRole();
                entity.Id = model.Id;
                entity.Name = model.Name;
                entity.Description = model.Description;
                entity.CreateTime = model.CreateTime;
                entity.CreatePerson = model.CreatePerson;
                if (m_Rep.Create(entity) == 1)
                {
                    //分配给角色
                    db.P_Sys_InsertSysRight();
                    //清理无用的项
                    db.P_Sys_ClearUnusedRightOperate();
                    return true;
                }
                else
                {
                    errors.Add(Suggestion.InsertFail);
                    return false;
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

        public bool Delete(ref ValidationErrors errors, string id)
        {
            try
            {
                if (m_Rep.Delete(id) == 1)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

        
        public bool Edit(ref ValidationErrors errors, SysRoleModel model)
        {
            try
            {
                SysRole entity = m_Rep.GetById(model.Id);
                if (entity == null)
                {
                    errors.Add(Suggestion.Disable);
                    return false;
                }
                entity.Id = model.Id;
                entity.Name = model.Name;
                entity.Description = model.Description;
                entity.CreateTime = model.CreateTime;
                entity.CreatePerson = model.CreatePerson;

               if (m_Rep.Edit(entity) == 1)
                {
                    return true;
                }
                else
                {
                    errors.Add(Suggestion.EditFail);
                    return false;
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

        public bool IsExists(string id)
        {
            if (db.SysRole.SingleOrDefault(a => a.Id == id) != null)
           {
                return true;
           }
            return false;
        }

        public SysRoleModel GetById(string id)
        {
            if (IsExist(id))
            {
                SysRole entity = m_Rep.GetById(id);
                SysRoleModel model = new SysRoleModel();
                model.Id = entity.Id;
                model.Name = entity.Name;
                model.Description = entity.Description;
                model.CreateTime = entity.CreateTime;
                model.CreatePerson = entity.CreatePerson;
                return model;
            }
            else
            {
                return null;
            }
        }

        public bool IsExist(string id)
        {
            return m_Rep.IsExist(id);
        }


    
    }
 }




 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;

namespace App.Models.Sys
{
    public class SysRoleModel
    {

        public string Id { get; set; }

        [Display(Name = "角色名称")]
        public string Name { get; set; }
        
        [Display(Name = "说明")]
        public string Description { get; set; }
        [Display(Name = "创建时间")]
        public DateTime CreateTime { get; set; }
        [Display(Name = "创建人")]
        public string CreatePerson { get; set; }
        [Display(Name = "拥有的用户")]
        public string UserName { get; set; }//拥有的用户

        public string Flag { get; set; }//用户分配角色
    }
}
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using App.Common;
using App.Models;
using Microsoft.Practices.Unity;
using App.IBLL;

using App.Models.Sys;
namespace App.Admin.Controllers
{
    public class SysRoleController : BaseController
    {
        //
        // GET: /SysRole/
        [Dependency]
        public ISysRoleBLL m_BLL { get; set; }
        ValidationErrors errors = new ValidationErrors();

        [SupportFilter]
        public ActionResult Index()
        {
            ViewBag.Perm = GetPermission();
            return View();
        }
        [SupportFilter(ActionName="Index")]
        public JsonResult GetList(GridPager pager,string queryStr)
        {
            List<SysRoleModel> list = m_BLL.GetList(ref pager, queryStr);
            var json = new
            {
                total = pager.totalRows,
                rows = (from r in list
                        select new SysRoleModel()
                        {

                            Id = r.Id,
                            Name = r.Name,
                            Description = r.Description,
                            CreateTime = r.CreateTime,
                            CreatePerson = r.CreatePerson,
                            UserName = r.UserName

                        }).ToArray()

            };

            return Json(json);
        }


        #region 创建
        [SupportFilter]
        public ActionResult Create()
        {
            ViewBag.Perm = GetPermission();
            return View();
        }

        [HttpPost]
        [SupportFilter]
        public JsonResult Create(SysRoleModel model)
        {
            model.Id = ResultHelper.NewId;
            model.CreateTime = ResultHelper.NowTime;
            if (model != null && ModelState.IsValid)
            {

                if (m_BLL.Create(ref errors, model))
                {
                    LogHandler.WriteServiceLog(GetUserId(), "Id" + model.Id + ",Name" + model.Name, "成功", "创建", "SysRole");
                    return Json(JsonHandler.CreateMessage(1, Suggestion.InsertSucceed));
                }
                else
                {
                    string ErrorCol = errors.Error;
                    LogHandler.WriteServiceLog(GetUserId(), "Id" + model.Id + ",Name" + model.Name + "," + ErrorCol, "失败", "创建", "SysRole");
                    return Json(JsonHandler.CreateMessage(0, Suggestion.InsertFail + ErrorCol));
                }
            }
            else
            {
                return Json(JsonHandler.CreateMessage(0, Suggestion.InsertFail));
            }
        }
        #endregion

        #region 修改
        [SupportFilter]
        public ActionResult Edit(string id)
        {
            ViewBag.Perm = GetPermission();
            SysRoleModel entity = m_BLL.GetById(id);
            return View(entity);
        }

        [HttpPost]
        [SupportFilter]
        public JsonResult Edit(SysRoleModel model)
        {
            if (model != null && ModelState.IsValid)
            {

                if (m_BLL.Edit(ref errors, model))
                {
                    LogHandler.WriteServiceLog(GetUserId(), "Id" + model.Id + ",Name" + model.Name, "成功", "修改", "SysRole");
                    return Json(JsonHandler.CreateMessage(1, Suggestion.EditSucceed));
                }
                else
                {
                    string ErrorCol = errors.Error;
                    LogHandler.WriteServiceLog(GetUserId(), "Id" + model.Id + ",Name" + model.Name + "," + ErrorCol, "失败", "修改", "SysRole");
                    return Json(JsonHandler.CreateMessage(0, Suggestion.EditFail + ErrorCol));
                }
            }
            else
            {
                return Json(JsonHandler.CreateMessage(0, Suggestion.EditFail));
            }
        }
        #endregion

        #region 详细
        [SupportFilter]
        public ActionResult Details(string id)
        {
            ViewBag.Perm = GetPermission();
            SysRoleModel entity = m_BLL.GetById(id);
            return View(entity);
        }

        #endregion

        #region 删除
        [HttpPost]
        [SupportFilter]
        public JsonResult Delete(string id)
        {
            if (!string.IsNullOrWhiteSpace(id))
            {
                if (m_BLL.Delete(ref errors, id))
                {
                    LogHandler.WriteServiceLog(GetUserId(), "Id:" + id, "成功", "删除", "SysRole");
                    return Json(JsonHandler.CreateMessage(1, Suggestion.DeleteSucceed));
                }
                else
                {
                    string ErrorCol = errors.Error;
                    LogHandler.WriteServiceLog(GetUserId(), "Id" + id + "," + ErrorCol, "失败", "删除", "SysRole");
                    return Json(JsonHandler.CreateMessage(0, Suggestion.DeleteFail + ErrorCol));
                }
            }
            else
            {
                return Json(JsonHandler.CreateMessage(0, Suggestion.DeleteFail));
            }


        }
        #endregion

    }
}
@using App.Admin;
@using App.Common;
@using App.Models.Sys;

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Index_Layout.cshtml";
    
    List<permModel> perm = (List<permModel>)ViewBag.Perm;
    if (perm == null)
    {
        perm = new List<permModel>();
    }
}
<div class="mvctool">
<input id="txtQuery" type="text" class="searchText"/>
@Html.ToolButton("btnQuery", "icon-search", "查询", perm, "Query", true)
@Html.ToolButton("btnCreate", "icon-add", "新增", perm, "Create", true)
@Html.ToolButton("btnEdit", "icon-edit", "编辑", perm, "Edit", true)
@Html.ToolButton("btnDetails", "icon-details", "详细", perm, "Details", true)
@Html.ToolButton("btnDelete", "icon-remove", "删除", perm, "Delete", true)
@Html.ToolButton("btnAllot", "icon-share", "分配用户", perm, "Allot", true)

</div>
<div id="modalwindow" class="easyui-window" data-options="modal:true,closed:true,minimizable:false,shadow:false"></div>
<table id="List"></table>
<script type="text/javascript">
    $(function () {
        $('#List').datagrid({
            url: '@Url.Action("GetList")',
            width: $(window).width() - 10,
            methord: 'post',
            height: $(window).height() - 35,
            fitColumns: true,
            sortName: 'CreateTime',
            sortOrder: 'desc',
            idField: 'Id',
            pageSize: 15,
            pageList: [15, 20, 30, 40, 50],
            pagination: true,
            striped: true, //奇偶行是否区分
            singleSelect: true,//单选模式
            //rownumbers: true,//行号
            columns: [[
                { field: 'Id', title: 'ID', width: 80, hidden: true },
                { field: 'Name', title: '角色名称', width: 80, sortable: true },
                { field: 'Description', title: '说明', width: 80, sortable: true },
                { field: 'CreateTime', title: '创建时间', width: 80, sortable: true },
                { field: 'CreatePerson', title: '创建人', width: 80, sortable: true },
                { field: 'UserName', title: '属下管理员', width: 80, sortable: true }
            ]]
        });
     });
    //ifram 返回
    function frameReturnByClose() {
        $("#modalwindow").window('close');
    }
    function frameReturnByReload(flag) {
        if (flag)
            $("#List").datagrid('load');
        else
            $("#List").datagrid('reload');
    }
    function frameReturnByMes(mes) {
        $.messageBox5s('提示', mes);
    }
    $(function () {
        $("#btnExport").click(function () {
            $("#modalwindow").html("<iframe width='100%' height='98%' scrolling='no' frameborder='0'' src='/SysHelper/ReportControl'></iframe>");
            $("#modalwindow").window({ title: '导出', width: 320, height: 200, iconCls: 'icon-add' }).window('open');
        });
        $("#btnCreate").click(function () {
            $("#modalwindow").html("<iframe width='100%' height='98%' scrolling='no' frameborder='0'' src='/SysRole/Create'></iframe>");
            $("#modalwindow").window({ title: '新增', width: 700, height: 400, iconCls: 'icon-add' }).window('open');
        });
        $("#btnEdit").click(function () {
            var row = $('#List').datagrid('getSelected');
            if (row != null) {
                $("#modalwindow").html("<iframe width='100%' height='99%'  frameborder='0' src='/SysRole/Edit?id=" + row.Id + "&Ieguid=" + GetGuid() + "'></iframe>");
                $("#modalwindow").window({ title: '编辑', width: 700, height: 430, iconCls: 'icon-edit' }).window('open');
            } else { $.messageBox5s('提示', '@Suggestion.PlaseChooseToOperatingRecords'); }
        });
        $("#btnDetails").click(function () {
            var row = $('#List').datagrid('getSelected');
            if (row != null) {
                $("#modalwindow").html("<iframe width='100%' height='98%' scrolling='no' frameborder='0' src='/SysRole/Details?id=" + row.Id + "&Ieguid=" + GetGuid() + "'></iframe>");
                $("#modalwindow").window({ title: '详细', width: 500, height: 300, iconCls: 'icon-details' }).window('open');
            } else { $.messageBox5s('提示', '@Suggestion.PlaseChooseToOperatingRecords'); }
        });
        $("#btnQuery").click(function () {
            var queryStr = $("#txtQuery").val();
            if (queryStr == null) {
                queryStr = "%";
            }
            $('#List').datagrid({
                url: '@Url.Action("GetList")?queryStr=' + encodeURI(queryStr)
            });

        });
        $("#btnDelete").click(function () {
            var row = $('#List').datagrid('getSelected');
            if (row != null) {
                $.messager.confirm('提示', '@Suggestion.YouWantToDeleteTheSelectedRecords', function (r) {
                    if (r) {
                        $.post("@Url.Action("Delete")?id=" + row.Id, function (data) {
                                if (data.type == 1)
                                    $("#List").datagrid('load');
                                $.messageBox5s('提示', data.message);
                            }, "json");

                        }
                });
                } else { $.messageBox5s('提示', '@Suggestion.PlaseChooseToOperatingRecords'); }
        });
        $("#btnAllot").click(function () {
            
        });
    });
</script>
@Html.Partial("~/Views/Shared/_Partial_AutoGrid.cshtml")
<!--自动GRID 从第一次加载与重置窗体大小时候发生的事件:分部视图,当只有一个Grid时且ID为List-->
<script type="text/javascript">
    $(function () {
        $(window).resize(function () {
            $('#List').datagrid('resize', {
                width: $(window).width() - 10,
                height: SetGridHeightSub(39)
            }).datagrid('resize', {
                width: $(window).width() - 10,
                height: SetGridHeightSub(39)
            });
        });
        
    });
</script>

我们注重的是效果,看下

由于我们的用户管理还没做,分配还不能做,所以就先给个空的值吧。

我们能够这么机械性全靠我们的架构,才能这么清晰的分析问题。

做了这么久不知道大家有没有发现,层层扣层层,异常捕获,异常记录,日志记录,反转控制,系统的可维护性非常的高,一目了然,这也是发布文章这么久,没人质疑这个架构的所在之处(我们是不是应该自豪一下

上面的图已经好了,关于记录,那必须是要有新增修改功能了,这个留给大家自己动手做做,因为这节是没有好讲的,这是为了下一节的,权限设置做铺垫而已。

谢谢大家

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏c#开发者

为什么nhibernate 不能保存on-to-many的结构

下面是主类文件 Code namespace EasyTalk.Module {     /// <summary>     /// SiteAddre...

27250
来自专栏张善友的专栏

Mono 3.2 测试NPinyin 中文转换拼音代码

C#中文转换为拼音NPinyin代码  在Mono 3.2下运行正常,Spacebuilder 有使用到NPinyin组件,代码兼容性没有问题。 using S...

22370
来自专栏飞扬的花生

Html5上传插件封装

      前段时间将flash的上传控件替换成使用纯js实现的,在此记录 1.创建标签 <div class="camera-area" style="dis...

45980
来自专栏跟着阿笨一起玩NET

c# 使用timer定时器操作,上次定时到了以后,下次还未执行完怎么处理

------解决方案-------------------------------------------------------- 开始的时候,禁用定时器,你...

93210
来自专栏Java成神之路

极光推送_总结_01_Java实现极光推送

19230
来自专栏跟着阿笨一起玩NET

关于asp.net与winform导出excel的代码

一、asp.net中导出Execl的方法: 在asp.net中导出Execl有两种方法,一种是将导出的文件存放在服务器某个文件夹下面,然后将文件地址输出在...

12910
来自专栏ASP.NET MVC5 后台权限管理系统

ASP.NET MVC5+EF6+EasyUI 后台管理系统(58)-DAL层重构

前言:这是对本文系统一次重要的革新,很久就想要重构数据访问层了,数据访问层重复代码太多。主要集中增删该查每个模块都有,所以本次是为封装相同接口方法    如果你...

34560
来自专栏菩提树下的杨过

asp.net与asp的session共享 及 asp的请求拦截

asp.net 与 asp 的session是无法直接共享的(底层的处理dll也不一样),要想互通session,只能用变通的办法: 一、asp.net -> ...

27470
来自专栏魏琼东

本人为巨杉数据库(开源NoSQL)写的C#驱动,支持Linq,全部开源,已提交github

     这些年在做AgileEAS.NET SOA 中间件平台的推广、技术咨询服务过程之中,特别是针对我们最熟悉的医疗行业应用之中,针对大数据分析,大并发性能...

12900
来自专栏草根专栏

设计模式学习(二): 观察者模式 (C#)

《深入浅出设计模式》学习笔记第二章 需求: 开发一套气象监测应用,如图: ? 气象站,目前有三种装置,温度、湿度和气压感应装置。 WeatherData对象追踪...

35050

扫码关注云+社区

领取腾讯云代金券