ASP.NET MVC5+EF6+EasyUI 后台管理系统(22)-权限管理系统-模块导航制作

来源:互联网 发布:高中化学软件下载 编辑:程序博客网 时间:2024/05/20 04:26
系列目录

最近比较忙,系统难度独步增加,文章的发布速度明显比以前慢了。

由于我们已经跑通了整个系统,所有东西都回到了简单,接下来我们做模块制作也就是操作SysModule表。

首先我们来回顾一下之前的难点主要就是SysRight这个表Rightflag字段的改变,这个字段关系导航与角色组的关系显示(即有权限时候显示菜单导航,这个更新讲到授权讲到,在这里浮头一下)

所以我们操作SysModule必须更新SysRight这张表,把模块先分配给角色

所以思路已经比较明显和简单了,这里我们模块将用treegrid来做,同时也间接学习怎么用treegrid,我之前也没用过easyui的datagrid,系统是jqgrid

这里用到权限控制了,所以你必须为SysModule添加增加,删除,修改等权限,并为admin用户授权,添加权限跳转到第十八讲 (必须非常熟练这一步,多用手动插入数据)

在此之前,由于我之前没用过treegrid不知道有个字段state(展开或者关闭属性)与数据库表SysModule的state字段冲突。然后更新EF

所以我们要修改一下SysModule的State变成Enable

添加后,我们依旧添加SysModule和SysModuleOperate模块的DAL BLL Model层代码(老套路了)

using System;using System.Collections.Generic;using System.Linq;using System.Text;using App.Models;namespace App.IDAL{    public interface ISysModuleRepository    {        IQueryable<SysModule> GetList(DBContainer db);        IQueryable<SysModule> GetModuleBySystem(DBContainer db,string parentId);        int Create(SysModule entity);        void Delete(DBContainer db, string id);        int Edit(SysModule entity);        SysModule GetById(string id);        bool IsExist(string id);    }}
ISysModuleRepository
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 SysModuleRepository : IDisposable,ISysModuleRepository    {        public IQueryable<SysModule> GetList(DBContainer db)        {            IQueryable<SysModule> list = db.SysModule.AsQueryable();            return list;        }        public IQueryable<SysModule> GetModuleBySystem(DBContainer db, string parentId)        {            return db.SysModule.Where(a => a.ParentId == parentId).AsQueryable();        }        public int Create(SysModule entity)        {            using (DBContainer db = new DBContainer())            {                db.SysModule.AddObject(entity);                return db.SaveChanges();            }        }        public void Delete(DBContainer db, string id)        {            SysModule entity = db.SysModule.SingleOrDefault(a => a.Id == id);            if (entity != null)            {                                //删除SysRight表数据                var sr = db.SysRight.AsQueryable().Where(a=>a.ModuleId==id);                foreach(var o in sr)                {                    //删除SysRightOperate表数据                    var sro= db.SysRightOperate.AsQueryable().Where(a=>a.RightId==o.Id);                    foreach(var o2 in sro)                    {                        db.SysRightOperate.DeleteObject(o2);                    }                    db.SysRight.DeleteObject(o);                }                //删除SysModuleOperate数据                var smo = db.SysModuleOperate.AsQueryable().Where(a => a.ModuleId == id);                foreach (var o3 in smo)                {                    db.SysModuleOperate.DeleteObject(o3);                }                db.SysModule.DeleteObject(entity);            }        }        public int Edit(SysModule entity)        {            using (DBContainer db = new DBContainer())            {                db.SysModule.Attach(entity);                db.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);                return db.SaveChanges();            }        }        public SysModule GetById(string id)        {            using (DBContainer db = new DBContainer())            {                return db.SysModule.SingleOrDefault(a => a.Id == id);            }        }        public bool IsExist(string id)        {            using (DBContainer db = new DBContainer())            {                SysModule entity = GetById(id);                if (entity != null)                    return true;                return false;            }        }        public void Dispose()        {        }    }}
SysModuleRepository
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 ISysModuleBLL    {        List<SysModuleModel> GetList(string parentId);        List<SysModule> GetModuleBySystem(string parentId);        bool Create(ref ValidationErrors errors, SysModuleModel model);        bool Delete(ref ValidationErrors errors, string id);        bool Edit(ref ValidationErrors errors, SysModuleModel model);        SysModuleModel GetById(string id);        bool IsExist(string id);    }}
ISysModuleBLL
using System;using System.Collections.Generic;using System.Linq;using System.Text;using App.IBLL;using Microsoft.Practices.Unity;using App.IDAL;using App.Models;using App.BLL.Core;using App.Common;using System.Transactions;using App.Models.Sys;namespace App.BLL{    public class SysModuleBLL:BaseBLL, ISysModuleBLL    {        [Dependency]        public ISysModuleRepository m_Rep { get; set; }        public List<SysModuleModel> GetList(string parentId)        {            IQueryable<SysModule> queryData = null;            queryData = m_Rep.GetList(db).Where(a => a.ParentId == parentId).OrderBy(a => a.Sort);            return CreateModelList(ref queryData);        }        private List<SysModuleModel> CreateModelList(ref IQueryable<SysModule> queryData)        {            List<SysModuleModel> modelList = (from r in queryData                                              select new SysModuleModel                                              {                                                  Id = r.Id,                                                  Name = r.Name,                                                  EnglishName = r.EnglishName,                                                  ParentId = r.ParentId,                                                  Url = r.Url,                                                  Iconic = r.Iconic,                                                  Sort = r.Sort,                                                  Remark = r.Remark,                                                  Enable = r.Enable,                                                  CreatePerson = r.CreatePerson,                                                  CreateTime = r.CreateTime,                                                  IsLast = r.IsLast                                              }).ToList();            return modelList;        }           public List<SysModule> GetModuleBySystem(string parentId)        {            return m_Rep.GetModuleBySystem(db,parentId).ToList();        }        public bool Create(ref ValidationErrors errors, SysModuleModel model)        {            try            {                SysModule entity = m_Rep.GetById(model.Id);                if (entity != null)                {                    errors.Add(Suggestion.PrimaryRepeat);                    return false;                }                entity = new SysModule();                entity.Id = model.Id;                entity.Name = model.Name;                entity.EnglishName = model.EnglishName;                entity.ParentId = model.ParentId;                entity.Url = model.Url;                entity.Iconic = model.Iconic;                entity.Sort = model.Sort;                entity.Remark = model.Remark;                entity.Enable = model.Enable;                entity.CreatePerson = model.CreatePerson;                entity.CreateTime = model.CreateTime;                entity.IsLast = model.IsLast;                if (m_Rep.Create(entity)==1)                {                    //分配给角色                    db.P_Sys_InsertSysRight();                    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 (db.SysModule.AsQueryable().Where(a=>a.SysModule2.Id==id).Count()>0)                {                    errors.Add("有下属关联,请先删除下属!");                    return false;                }                m_Rep.Delete(db, id);                if (db.SaveChanges() > 0)                {                    //清理无用的项                    db.P_Sys_ClearUnusedRightOperate();                    return true;                }                else                {                    return false;                }            }            catch (Exception ex)            {                errors.Add(ex.Message);                ExceptionHander.WriteException(ex);                return false;            }        }                public bool Edit(ref ValidationErrors errors, SysModuleModel model)        {            try            {                SysModule entity = m_Rep.GetById(model.Id);                if (entity == null)                {                    errors.Add(Suggestion.Disable);                    return false;                }                entity.Name = model.Name;                entity.EnglishName = model.EnglishName;                entity.ParentId = model.ParentId;                entity.Url = model.Url;                entity.Iconic = model.Iconic;                entity.Sort = model.Sort;                entity.Remark = model.Remark;                entity.Enable = model.Enable;                entity.IsLast = model.IsLast;                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 SysModuleModel GetById(string id)        {            if (IsExist(id))            {                SysModule entity = m_Rep.GetById(id);                SysModuleModel model = new SysModuleModel();                model.Id = entity.Id;                model.Name = entity.Name;                model.EnglishName = entity.EnglishName;                model.ParentId = entity.ParentId;                model.Url = entity.Url;                model.Iconic = entity.Iconic;                model.Sort = entity.Sort;                model.Remark = entity.Remark;                model.Enable = entity.Enable;                model.CreatePerson = entity.CreatePerson;                model.CreateTime = entity.CreateTime;                model.IsLast = entity.IsLast;                return model;            }            else            {                return null;            }        }        public bool IsExist(string id)        {            return m_Rep.IsExist(id);        }    }}
SysModuleBLL
//------------------------------------------------------------------------------// <auto-generated>//     此代码由T4模板自动生成//       生成时间 2012-12-25 15:33:37 by App//     对此文件的更改可能会导致不正确的行为,并且如果//     重新生成代码,这些更改将会丢失。// </auto-generated>//------------------------------------------------------------------------------using System;using System.ComponentModel.DataAnnotations;namespace App.Models.Sys{    public class SysModuleModel    {        [Display(Name = "ID")]        public string Id { get; set; }        [Display(Name = "名称")]        public string Name { get; set; }        [Display(Name = "别名")]        public string EnglishName { get; set; }        [Display(Name = "上级ID")]        public string ParentId { get; set; }        [Display(Name = "链接")]        public string Url { get; set; }        [Display(Name = "图标")]        public string Iconic { get; set; }        [Display(Name = "排序号")]        public int? Sort { get; set; }        [Display(Name = "说明")]        public string Remark { get; set; }        [Display(Name = "状态")]        public bool Enable { get; set; }        [Display(Name = "创建人")]        public string CreatePerson { get; set; }        [Display(Name = "创建时间")]        public DateTime? CreateTime { get; set; }        [Display(Name = "是否最后一项")]        public bool IsLast { get; set; }        public string state { get; set; }//treegrid    }}
SysModuleModel

-----------------------------------丑陋的分割线----------------------------------------

using App.Models;using System.Linq;namespace App.IDAL{    public interface ISysModuleOperateRepository    {        IQueryable<SysModuleOperate> GetList(DBContainer db);        int Create(SysModuleOperate entity);        int Delete(string id);        SysModuleOperate GetById(string id);        bool IsExist(string id);    }}
ISysModuleOperateRepository
using System;using System.Linq;using App.Models;using System.Data;using App.IDAL;namespace App.DAL{    public class SysModuleOperateRepository : ISysModuleOperateRepository, IDisposable    {        public IQueryable<SysModuleOperate> GetList(DBContainer db)        {            IQueryable<SysModuleOperate> list = db.SysModuleOperate.AsQueryable();            return list;        }        public int Create(SysModuleOperate entity)        {            using (DBContainer db = new DBContainer())            {                db.SysModuleOperate.AddObject(entity);                return db.SaveChanges();            }        }        public int Delete(string id)        {            using (DBContainer db = new DBContainer())            {                SysModuleOperate entity = db.SysModuleOperate.SingleOrDefault(a => a.Id == id);                if (entity != null)                {                    db.SysModuleOperate.DeleteObject(entity);                }                return db.SaveChanges();            }        }        public SysModuleOperate GetById(string id)        {            using (DBContainer db = new DBContainer())            {                return db.SysModuleOperate.SingleOrDefault(a => a.Id == id);            }        }        public bool IsExist(string id)        {            using (DBContainer db = new DBContainer())            {                SysModuleOperate entity = GetById(id);                if (entity != null)                    return true;                return false;            }        }        public void Dispose()        {        }    }}
SysModuleOperateRepository
using System.Collections.Generic;using App.Common;using App.Models.Sys;namespace App.IBLL{    public interface ISysModuleOperateBLL    {        List<SysModuleOperateModel> GetList(ref GridPager pager, string queryStr);        bool Create(ref ValidationErrors errors, SysModuleOperateModel model);        bool Delete(ref ValidationErrors errors, string id);        SysModuleOperateModel GetById(string id);        bool IsExist(string id);    }}
ISysModuleOperateBLL
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 SysModuleOperateBLL : BaseBLL, ISysModuleOperateBLL    {        [Dependency]        public ISysModuleOperateRepository m_Rep { get; set; }        public List<SysModuleOperateModel> GetList(ref GridPager pager, string mid)        {            IQueryable<SysModuleOperate> queryData = m_Rep.GetList(db).Where(a => a.ModuleId == mid);            pager.totalRows = queryData.Count();            queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);            return CreateModelList(ref queryData);        }        private List<SysModuleOperateModel> CreateModelList(ref IQueryable<SysModuleOperate> queryData)        {            List<SysModuleOperateModel> modelList = (from r in queryData                                                     select new SysModuleOperateModel                                                     {                                                         Id = r.Id,                                                         Name = r.Name,                                                         KeyCode = r.KeyCode,                                                         ModuleId = r.ModuleId,                                                         IsValid = r.IsValid,                                                         Sort = r.Sort                                                     }).ToList();            return modelList;        }        public bool Create(ref ValidationErrors errors, SysModuleOperateModel model)        {            try            {                SysModuleOperate entity = m_Rep.GetById(model.Id);                if (entity != null)                {                    errors.Add(Suggestion.PrimaryRepeat);                    return false;                }                entity = new SysModuleOperate();                entity.Id = model.Id;                entity.Name = model.Name;                entity.KeyCode = model.KeyCode;                entity.ModuleId = model.ModuleId;                entity.IsValid = model.IsValid;                entity.Sort = model.Sort;                if (m_Rep.Create(entity) == 1)                {                    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 IsExists(string id)        {            if (db.SysModuleOperate.SingleOrDefault(a => a.Id == id) != null)            {                return true;            }            return false;        }        public SysModuleOperateModel GetById(string id)        {            if (IsExist(id))            {                SysModuleOperate entity = m_Rep.GetById(id);                SysModuleOperateModel model = new SysModuleOperateModel();                model.Id = entity.Id;                model.Name = entity.Name;                model.KeyCode = entity.KeyCode;                model.ModuleId = entity.ModuleId;                model.IsValid = entity.IsValid;                model.Sort = entity.Sort;                return model;            }            else            {                return null;            }        }        public bool IsExist(string id)        {            return m_Rep.IsExist(id);        }    }}
SysModuleOperateBLL
//------------------------------------------------------------------------------// <auto-generated>//     此代码由T4模板自动生成//       生成时间 2012-12-25 17:15:28 by App//     对此文件的更改可能会导致不正确的行为,并且如果//     重新生成代码,这些更改将会丢失。// </auto-generated>//------------------------------------------------------------------------------using System;using System.ComponentModel.DataAnnotations;namespace App.Models.Sys{    public class SysModuleOperateModel    {        [Display(Name = "ID")]        public string Id { get; set; }        [Display(Name = "操作名称")]        public string Name { get; set; }        [Display(Name = "操作码")]        public string KeyCode { get; set; }        [Display(Name = "所属模块")]        public string ModuleId { get; set; }        [Display(Name = "是否验证")]        public bool IsValid { get; set; }        [Required(ErrorMessage = "{0}必须填写")]        [Display(Name = "排序号")]        public int Sort { get; set; }    }}
SysModuleOperateModel

-----------------------------------丑陋的分割线----------------------------------------

在BaseController添加方法(获取当前页或操作访问权限)

/// <summary>        /// 获取当前页或操作访问权限        /// </summary>        /// <returns>权限列表</returns>        public List<permModel> GetPermission()        {            string filePath = HttpContext.Request.FilePath;            List<permModel> perm = (List<permModel>)Session[filePath];            return perm;        }
GetPermission()

控制器

//------------------------------------------------------------------------------// <auto-generated>//     此代码由T4模板自动生成//       生成时间 2012-12-25 15:31:19 by YmNets//     对此文件的更改可能会导致不正确的行为,并且如果//     重新生成代码,这些更改将会丢失。// </auto-generated>//------------------------------------------------------------------------------using System.Collections.Generic;using System.Linq;using System.Web.Mvc;using Microsoft.Practices.Unity;using App.IBLL;using App.Common;using App.Models;using App.Models.Sys;namespace App.Admin.Controllers{    public class SysModuleController : BaseController    {        /// <summary>        /// 业务层注入        /// </summary>        [Dependency]        public ISysModuleBLL m_BLL { get; set; }        [Dependency]        public ISysModuleOperateBLL operateBLL { get; set; }        ValidationErrors errors = new ValidationErrors();        /// <summary>        /// 主页        /// </summary>        /// <returns>视图</returns>        [SupportFilter]        public ActionResult Index()        {            ViewBag.Perm = GetPermission();            return View();        }        /// <summary>        /// 获取列表        /// </summary>        /// <param name="pager">分页</param>        /// <param name="queryStr">查询条件</param>        /// <returns></returns>        [SupportFilter(ActionName = "Index")]        [HttpPost]        public JsonResult GetList(string id)        {            if (id == null)                id = "0";            List<SysModuleModel> list = m_BLL.GetList(id);            var json = from r in list                       select new SysModuleModel()                       {                           Id = r.Id,                           Name = r.Name,                           EnglishName = r.EnglishName,                           ParentId = r.ParentId,                           Url = r.Url,                           Iconic = r.Iconic,                           Sort = r.Sort,                           Remark = r.Remark,                           Enable = r.Enable,                           CreatePerson = r.CreatePerson,                           CreateTime = r.CreateTime,                           IsLast = r.IsLast,                           state = (m_BLL.GetList(r.Id).Count > 0) ? "closed" : "open"                       };            return Json(json);        }        [HttpPost]        [SupportFilter(ActionName = "Index")]        public JsonResult GetOptListByModule(GridPager pager, string mid)        {            pager.rows = 1000;            pager.page = 1;            List<SysModuleOperateModel> list = operateBLL.GetList(ref pager, mid);            var json = new            {                total = pager.totalRows,                rows = (from r in list                        select new SysModuleOperateModel()                        {                    Id = r.Id,                    Name = r.Name,                    KeyCode = r.KeyCode,                    ModuleId = r.ModuleId,                    IsValid = r.IsValid,                    Sort = r.Sort                        }).ToArray()            };            return Json(json);        }                    #region 创建模块        [SupportFilter]        public ActionResult Create(string id)        {            ViewBag.Perm = GetPermission();            SysModuleModel entity = new SysModuleModel()            {                ParentId = id,                Enable = true,                Sort = 0            };            return View(entity);        }        [HttpPost]        [SupportFilter]        public JsonResult Create(SysModuleModel model)        {            model.Id = ResultHelper.NewId;            model.CreateTime = ResultHelper.NowTime;            model.CreatePerson = GetUserId();            if (model != null && ModelState.IsValid)            {                if (m_BLL.Create(ref errors, model))                {                    LogHandler.WriteServiceLog(GetUserId(), "Id" + model.Id + ",Name" + model.Name, "成功", "创建", "SysModule");                    return Json(JsonHandler.CreateMessage(1, Suggestion.InsertSucceed));                }                else                {                    string ErrorCol = errors.Error;                    LogHandler.WriteServiceLog(GetUserId(), "Id" + model.Id + ",Name" + model.Name + "," + ErrorCol, "失败", "创建", "SysModule");                    return Json(JsonHandler.CreateMessage(0, Suggestion.InsertFail + ErrorCol));                }            }            else            {                return Json(JsonHandler.CreateMessage(0, Suggestion.InsertFail));            }        }        #endregion        #region 创建        [SupportFilter(ActionName = "Create")]        public ActionResult CreateOpt(string moduleId)        {            ViewBag.Perm = GetPermission();            SysModuleOperateModel sysModuleOptModel = new SysModuleOperateModel();            sysModuleOptModel.ModuleId = moduleId;            sysModuleOptModel.IsValid = true;            return View(sysModuleOptModel);        }        [HttpPost]        [SupportFilter(ActionName = "Create")]        public JsonResult CreateOpt(SysModuleOperateModel info)        {            if (info != null && ModelState.IsValid)            {                SysModuleOperateModel entity = operateBLL.GetById(info.Id);                if (entity != null)                    return Json(JsonHandler.CreateMessage(0, Suggestion.PrimaryRepeat), JsonRequestBehavior.AllowGet);                entity = new SysModuleOperateModel();                entity.Id = info.ModuleId + info.KeyCode;                entity.Name = info.Name;                entity.KeyCode = info.KeyCode;                entity.ModuleId = info.ModuleId;                entity.IsValid = info.IsValid;                entity.Sort = info.Sort;                if (operateBLL.Create(ref errors, entity))                {                    LogHandler.WriteServiceLog(GetUserId(), "Id:" + info.Id + ",Name:" + info.Name, "成功", "创建", "模块设置");                    return Json(JsonHandler.CreateMessage(1, Suggestion.InsertSucceed), JsonRequestBehavior.AllowGet);                }                else                {                    string ErrorCol = errors.Error;                    LogHandler.WriteServiceLog(GetUserId(), "Id:" + info.Id + ",Name:" + info.Name + "," + ErrorCol, "失败", "创建", "模块设置");                    return Json(JsonHandler.CreateMessage(0, Suggestion.InsertFail + ErrorCol), JsonRequestBehavior.AllowGet);                }            }            else            {                return Json(JsonHandler.CreateMessage(0, Suggestion.InsertFail), JsonRequestBehavior.AllowGet);            }        }        #endregion        #region 修改模块        [SupportFilter]        public ActionResult Edit(string id)        {            ViewBag.Perm = GetPermission();            SysModuleModel entity = m_BLL.GetById(id);            return View(entity);        }        [HttpPost]        [SupportFilter]        public JsonResult Edit(SysModuleModel model)        {            if (model != null && ModelState.IsValid)            {                if (m_BLL.Edit(ref errors, model))                {                    LogHandler.WriteServiceLog(GetUserId(), "Id" + model.Id + ",Name" + model.Name, "成功", "修改", "系统菜单");                    return Json(JsonHandler.CreateMessage(1, Suggestion.EditSucceed));                }                else                {                    string ErrorCol = errors.Error;                    LogHandler.WriteServiceLog(GetUserId(), "Id" + model.Id + ",Name" + model.Name + "," + ErrorCol, "失败", "修改", "系统菜单");                    return Json(JsonHandler.CreateMessage(0, Suggestion.EditFail + ErrorCol));                }            }            else            {                return Json(JsonHandler.CreateMessage(0, Suggestion.EditFail));            }        }        #endregion             #region 删除        [HttpPost]        [SupportFilter]        public JsonResult Delete(string id)        {            if (!string.IsNullOrWhiteSpace(id))            {                if (m_BLL.Delete(ref errors, id))                {                    LogHandler.WriteServiceLog(GetUserId(), "Ids:" + id, "成功", "删除", "模块设置");                    return Json(JsonHandler.CreateMessage(1, Suggestion.DeleteSucceed), JsonRequestBehavior.AllowGet);                }                else                {                    string ErrorCol = errors.Error;                    LogHandler.WriteServiceLog(GetUserId(), "Id:" + id + "," + ErrorCol, "失败", "删除", "模块设置");                    return Json(JsonHandler.CreateMessage(0, Suggestion.DeleteFail + ErrorCol), JsonRequestBehavior.AllowGet);                }            }            else            {                return Json(JsonHandler.CreateMessage(0, Suggestion.DeleteFail), JsonRequestBehavior.AllowGet);            }        }        [HttpPost]        [SupportFilter(ActionName = "Delete")]        public JsonResult DeleteOpt(string id)        {            if (!string.IsNullOrWhiteSpace(id))            {                if (operateBLL.Delete(ref errors, id))                {                    LogHandler.WriteServiceLog(GetUserId(), "Id:" + id, "成功", "删除", "模块设置KeyCode");                    return Json(JsonHandler.CreateMessage(1, Suggestion.DeleteSucceed), JsonRequestBehavior.AllowGet);                }                else                {                    string ErrorCol = errors.Error;                    LogHandler.WriteServiceLog(GetUserId(), "Id:" + id + "," + ErrorCol, "失败", "删除", "模块设置KeyCode");                    return Json(JsonHandler.CreateMessage(0, Suggestion.DeleteFail + ErrorCol), JsonRequestBehavior.AllowGet);                }            }            else            {                return Json(JsonHandler.CreateMessage(0, Suggestion.DeleteFail), JsonRequestBehavior.AllowGet);            }        }        #endregion    }}
SysModuleController

补充ExtendMvcHtml这个类的重载!来根据权限获取菜单

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Web;using System.Web.Mvc;using App.Models.Sys; namespace App.Admin{    public static class ExtendMvcHtml    {        /// <summary>        /// 权限按钮        /// </summary>        /// <param name="helper">htmlhelper</param>        /// <param name="id">控件Id</param>        /// <param name="icon">控件icon图标class</param>        /// <param name="text">控件的名称</param>        /// <param name="perm">权限列表</param>        /// <param name="keycode">操作码</param>        /// <param name="hr">分割线</param>        /// <returns>html</returns>        public static MvcHtmlString ToolButton(this HtmlHelper helper, string id, string icon, string text, List<permModel> perm, string keycode, bool hr)        {            if (perm.Where(a => a.KeyCode == keycode).Count() > 0)            {                StringBuilder sb = new StringBuilder();                sb.AppendFormat("<a id=\"{0}\" style=\"float: left;\" class=\"l-btn l-btn-plain\">", id);                sb.AppendFormat("<span class=\"l-btn-left\"><span class=\"l-btn-text {0}\" style=\"padding-left: 20px;\">", icon);                sb.AppendFormat("{0}</span></span></a>", text);                if (hr)                {                    sb.Append("<div class=\"datagrid-btn-separator\"></div>");                }                return new MvcHtmlString(sb.ToString());            }            else            {                return new MvcHtmlString("");            }        }        /// <summary>        /// 普通按钮        /// </summary>        /// <param name="helper">htmlhelper</param>        /// <param name="id">控件Id</param>        /// <param name="icon">控件icon图标class</param>        /// <param name="text">控件的名称</param>        /// <param name="hr">分割线</param>        /// <returns>html</returns>        public static MvcHtmlString ToolButton(this HtmlHelper helper, string id, string icon, string text, bool hr)        {             StringBuilder sb = new StringBuilder();            sb.AppendFormat("<a id=\"{0}\" style=\"float: left;\" class=\"l-btn l-btn-plain\">", id);            sb.AppendFormat("<span class=\"l-btn-left\"><span class=\"l-btn-text {0}\" style=\"padding-left: 20px;\">", icon);            sb.AppendFormat("{0}</span></span></a>", text);            if (hr)            {                sb.Append("<div class=\"datagrid-btn-separator\"></div>");            }            return new MvcHtmlString(sb.ToString());         }    }}
ExtendMvcHtml

视图

@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>();    }}<table>    <tr>        <td style="vertical-align:top">            <div class="mvctool">                @Html.ToolButton("btnCreate", "icon-add", "新增", perm, "Create", true)                 @Html.ToolButton("btnEdit", "icon-edit", "编辑", perm, "Edit", true)                @Html.ToolButton("btnDelete", "icon-remove", "删除", perm, "Delete", true)            </div>            <table id="List"></table>        </td>        <td style="width: 210px; padding-left: 5px; vertical-align:top">            <div class="mvctool">                @Html.ToolButton("btnCreateOpt", "icon-add", "新增操作码", perm, "Create", true)                @Html.ToolButton("btnDeleteOpt", "icon-remove", "删除操作码", perm, "Delete", true)            </div>            <table id="OptList"></table>        </td>    </tr></table><div id="modalwindow" class="easyui-window" data-options="modal:true,closed:true,minimizable:false,shadow:false"></div><script type="text/javascript">    $(function () {        $('#List').treegrid({            url: '@Url.Action("GetList")',            width: $(window).width() - 270,                methord: 'post',                height: $(window).height() - 35,                fitColumns: true,                treeField: 'Name',                idField: 'Id',                pagination: false,                striped: true, //奇偶行是否区分                singleSelect: true,//单选模式                //rownumbers: true,//行号                columns: [[                    { field: 'Id', title: '唯一标识', width: 120},                    { field: 'Name', title: '名称', width: 220, sortable: true },                    { field: 'EnglishName', title: '英文名称', width: 80, sortable: true,hidden:true },                    { field: 'ParentId', title: '上级Id', width: 80, sortable: true },                    { field: 'Url', title: '链接地址', width: 80, sortable: true },                    { field: 'Iconic', title: '图标', width: 80, sortable: true },                    { field: 'Sort', title: '排序号', width: 80, sortable: true },                    { field: 'Remark', title: '说明', width: 80, sortable: true },                     {                         field: 'Enable', title: '是否启用', width: 60,align:'center', formatter: function (value) {                             if (value) {                                 return "<img src='/Content/Images/icon/pass.png'/>";                             } else {                                 return "<img src='/Content/Images/icon/no.png'/>";                             }                         }                     },                    { field: 'CreatePerson', title: '创建人', width: 80, sortable: true },                    { field: 'CreateTime', title: '创建时间', width: 120, sortable: true },                    {                        field: 'IsLast', title: '是否最后一项', align: 'center', width: 100, formatter: function (value) {                            if (value) {                                return "";                            } else {                                return "";                            }                        }                    },                ]],                onClickRow: function (index, data) {                    var row = $('#List').treegrid('getSelected');                    if (row != null) {                        $('#OptList').datagrid({                            url: '@Url.Action("GetOptListByModule")?mid=' + row.Id                         });                    }                }            });        $('#OptList').datagrid({            url: '@Url.Action("GetOptListByModule")',            width: 255,            methord: 'post',            height: $(window).height() - 35,            fitColumns: true,            sortName: 'Sort',            sortOrder: 'asc',            idField: 'Id',            pageSize: 1000,            pagination: false,            striped: true, //奇偶行是否区分            singleSelect: true,//单选模式            //rownumbers: true,//行号            columns: [[                { field: 'Id', title: '', width: 80, hidden: true },                { field: 'Name', title: '名称', width: 80, sortable: true },                { field: 'KeyCode', title: '操作码', width: 80, sortable: true },                { field: 'ModuleId', title: '所属模块', width: 80, sortable: true, hidden: true },                 {                     field: 'IsValid', title: '是否验证', width: 80, align: 'center', formatter: function (value) {                         if (value) {                             return "<img src='/Content/Images/icon/pass.png'/>";                         } else {                             return "<img src='/Content/Images/icon/no.png'/>";                         }                     }                 },                { field: 'Sort', title: '排序', width: 80, sortable: true }            ]]        });        //自动宽高        $(window).resize(function () {            $('#List').datagrid('resize', {                width: $(window).width() - 270,                height: $(window).height() - 35            }).datagrid('resize', {                width: $(window).width() - 270,                height: $(window).height() - 35            });            $('#OptList').datagrid('resize', {                height: $(window).height() - 35            }).datagrid('resize', {                height: $(window).height() - 35            });        });    });    //ifram 返回    function frameReturnByClose() {        $("#modalwindow").window('close');    }    function frameReturnByReload(flag) {        if (flag)            $("#List").treegrid('reload');        else            $("#List").treegrid('load');    }    function frameReturnByReloadOpt(flag) {        if (flag)            $("#OptList").datagrid('load');        else            $("#OptList").datagrid('reload');    }    function frameReturnByMes(mes) {        $.messageBox5s('提示', mes);    }    $(function () {        $("#btnCreate").click(function () {            var row = $('#List').treegrid('getSelected');            $("#modalwindow").html("<iframe width='100%' height='98%' scrolling='no' frameborder='0'' src='/SysModule/Create?id=" + (row != null ? row.Id : "0") + "&Ieguid=" + GetGuid() + "'></iframe>");            $("#modalwindow").window({ title: '新增', width: 700, height: 400, iconCls: 'icon-add' }).window('open');        });        $("#btnEdit").click(function () {            var row = $('#List').treegrid('getSelected');            if (row != null) {                $("#modalwindow").html("<iframe width='100%' height='99%'  frameborder='0' src='/SysModule/Edit?id=" + row.Id + "&Ieguid=" + GetGuid() + "'></iframe>");                $("#modalwindow").window({ title: '编辑', width: 700, height: 430, iconCls: 'icon-edit' }).window('open');            } else { $.messageBox5s('提示', '@Suggestion.PlaseChooseToOperatingRecords'); }        });        $("#btnDelete").click(function () {            var row = $('#List').treegrid('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").treegrid('reload');                            $.messageBox5s('提示', data.message);                        }, "json");                    }                });            } else { $.messageBox5s('提示', '@Suggestion.PlaseChooseToOperatingRecords'); }        });        $("#btnCreateOpt").click(function () {            var row = $('#List').treegrid('getSelected');            if (row != null) {                if (row.IsLast) {                    $("#modalwindow").html("<iframe width='100%' height='99%'  frameborder='0' src='/SysModule/CreateOpt?moduleId=" + row.Id + "&Ieguid=" + GetGuid() + "'></iframe>");                    $("#modalwindow").window({ title: '新增操作码', width: 500, height: 330, iconCls: 'icon-edit' }).window('open');                } else {                    $.messageBox5s('提示', '只有最后一项的菜单才能设置操作码!');                }                           } else { $.messageBox5s('提示', '请选择一个要赋予操作码的模块!'); }         });        $("#btnDeleteOpt").click(function () {            var row = $('#OptList').datagrid('getSelected');            if (row != null) {                $.messager.confirm('提示', '您确定要删除“' + row.Name+ '”这个操作码?', function (r) {                    if (r) {                        $.post("@Url.Action("DeleteOpt")?id=" + row.Id, function (data) {                            if (data.type == 1)                            {                                $("#OptList").datagrid('load');                            }                        }, "json");                    }                });            } else { $.messageBox5s('提示', '请选择一个要赋予操作码的模块!'); }         });    });</script>
Index.cshtml
@model App.Models.Sys.SysModuleModel@using App.Common;@using App.Models.Sys;@using App.Admin;@{    ViewBag.Title = "修改";    Layout = "~/Views/Shared/_Index_LayoutEdit.cshtml";    List<permModel> perm = (List<permModel>)ViewBag.Perm;    if (perm == null)    {        perm = new List<permModel>();    }}<script type="text/javascript">$(function () {    $("#btnSave").click(function () {        if ($("form").valid()) {            $.ajax({                url: "@Url.Action("Edit")",                type: "Post",                data: $("form").serialize(),                dataType: "json",                success: function (data) {                    if (data.type == 1) {                        window.parent.frameReturnByMes(data.message);                        window.parent.frameReturnByReload(true);                        window.parent.frameReturnByClose()                    }                    else {                        window.parent.frameReturnByMes(data.message);                    }                }            });        }        return false;    });    $("#btnReturn").click(function () {         window.parent.frameReturnByClose();    });});</script><div class="mvctool bgb">@Html.ToolButton("btnSave", "icon-save", "保存", perm, "Save", true)@Html.ToolButton("btnReturn", "icon-return", "返回",false)</div>@using (Html.BeginForm()){             @Html.HiddenFor(model => model.Id)             @Html.HiddenFor(model => model.CreateTime)             @Html.HiddenFor(model => model.CreatePerson) <table class="fromEditTable setTextWidth300">    <tbody>        <tr>            <td style="width:100px; text-align:right;">                @Html.LabelFor(model => model.Name):            </td>            <td style="width:310px">                @Html.EditorFor(model => model.Name)            </td>            <td>@Html.ValidationMessageFor(model => model.Name)</td>        </tr>        <tr>            <td style="width:100px; text-align:right;">                @Html.LabelFor(model => model.ParentId):            </td>            <td style="width:310px">                @Html.EditorFor(model => model.ParentId)            </td>            <td>@Html.ValidationMessageFor(model => model.ParentId)</td>        </tr>        <tr>            <td style="width:100px; text-align:right;">                @Html.LabelFor(model => model.Url):            </td>            <td style="width:310px">                @Html.EditorFor(model => model.Url)            </td>            <td>@Html.ValidationMessageFor(model => model.Url)</td>        </tr>        <tr>            <td style="width:100px; text-align:right;">                @Html.LabelFor(model => model.Iconic):            </td>            <td style="width:310px">                @Html.EditorFor(model => model.Iconic)            </td>            <td>@Html.ValidationMessageFor(model => model.Iconic)</td>        </tr>        <tr>            <td style="width:100px; text-align:right;">                @Html.LabelFor(model => model.Sort):            </td>            <td style="width:310px">                @Html.EditorFor(model => model.Sort)            </td>            <td>@Html.ValidationMessageFor(model => model.Sort)</td>        </tr>        <tr>            <td style="width:100px; text-align:right;">                @Html.LabelFor(model => model.Remark):            </td>            <td style="width:310px">                @Html.EditorFor(model => model.Remark)            </td>            <td>@Html.ValidationMessageFor(model => model.Remark)</td>        </tr>        <tr>            <td style="width:100px; text-align:right;">                @Html.LabelFor(model => model.Enable):            </td>            <td style="width:310px">                @Html.CheckBoxFor(model => model.Enable)            </td>            <td>@Html.ValidationMessageFor(model => model.Enable)</td>        </tr>        <tr>            <td style="width:100px; text-align:right;">                @Html.LabelFor(model => model.IsLast):            </td>            <td style="width:310px">                @Html.CheckBoxFor(model => model.IsLast)            </td>            <td>@Html.ValidationMessageFor(model => model.IsLast)</td>        </tr>           </tbody></table>}
Edit.cshtml
@model App.Models.Sys.SysModuleModel@using App.Common;@using App.Models.Sys;@using App.Admin;@{    ViewBag.Title = "创建";    Layout = "~/Views/Shared/_Index_LayoutEdit.cshtml";    List<permModel> perm = (List<permModel>)ViewBag.Perm;    if (perm == null)    {        perm = new List<permModel>();    }}<script type="text/javascript">    $(function () {        $("#btnSave").click(function () {            if ($("form").valid()) {                $.ajax({                    url: "@Url.Action("Create")",                type: "Post",                data: $("form").serialize(),                dataType: "json",                success: function (data) {                    if (data.type == 1) {                        window.parent.frameReturnByMes(data.message);                        window.parent.frameReturnByReload(true);                        window.parent.frameReturnByClose()                    }                    else {                        window.parent.frameReturnByMes(data.message);                    }                }            });        }        return false;    });    $("#btnReturn").click(function () {        window.parent.frameReturnByClose();    });});</script><div class="mvctool bgb">@Html.ToolButton("btnSave", "icon-save", "保存", perm, "Save", true)@Html.ToolButton("btnReturn", "icon-return", "返回",false)</div>@using (Html.BeginForm()){             @Html.HiddenFor(model => model.Id)             @Html.HiddenFor(model => model.CreateTime) <table class="fromEditTable setTextWidth300">    <tbody>        <tr>            <td style="width:100px; text-align:right;">                @Html.LabelFor(model => model.Name):            </td>            <td style="width:310px">                @Html.EditorFor(model => model.Name)            </td>            <td>@Html.ValidationMessageFor(model => model.Name)</td>        </tr>             <tr>            <td style="width:100px; text-align:right;">                @Html.LabelFor(model => model.ParentId):            </td>            <td style="width:310px">                @Html.EditorFor(model => model.ParentId)            </td>            <td>@Html.ValidationMessageFor(model => model.ParentId)</td>        </tr>        <tr>            <td style="width:100px; text-align:right;">                @Html.LabelFor(model => model.Url):            </td>            <td style="width:310px">                @Html.EditorFor(model => model.Url)            </td>            <td>@Html.ValidationMessageFor(model => model.Url)</td>        </tr>        <tr>            <td style="width:100px; text-align:right;">                @Html.LabelFor(model => model.Iconic):            </td>            <td style="width:310px">                @Html.EditorFor(model => model.Iconic)            </td>            <td>@Html.ValidationMessageFor(model => model.Iconic)</td>        </tr>        <tr>            <td style="width:100px; text-align:right;">                @Html.LabelFor(model => model.Sort):            </td>            <td style="width:310px">                @Html.EditorFor(model => model.Sort)            </td>            <td>@Html.ValidationMessageFor(model => model.Sort)</td>        </tr>        <tr>            <td style="width:100px; text-align:right;">                @Html.LabelFor(model => model.Remark):            </td>            <td style="width:310px">                @Html.EditorFor(model => model.Remark)            </td>            <td>@Html.ValidationMessageFor(model => model.Remark)</td>        </tr>        <tr>            <td style="width:100px; text-align:right;">                @Html.LabelFor(model => model.Enable):            </td>            <td style="width:310px">                @Html.CheckBoxFor(model => model.Enable,  new { @checked = true })            </td>            <td>@Html.ValidationMessageFor(model => model.Enable)</td>        </tr>            <tr>            <td style="width:100px; text-align:right;">                @Html.LabelFor(model => model.IsLast):            </td>            <td style="width:310px">                @Html.CheckBoxFor(model => model.IsLast,  new { @checked = true })            </td>            <td>@Html.ValidationMessageFor(model => model.IsLast)</td>        </tr>           </tbody></table>}
Create.cshtml
@model App.Models.Sys.SysModuleOperateModel@using App.Common;@using App.Models.Sys;@using App.Admin;@{    ViewBag.Title = "创建";    Layout = "~/Views/Shared/_Index_LayoutEdit.cshtml";    List<permModel> perm = (List<permModel>)ViewBag.Perm;    if (perm == null)    {        perm = new List<permModel>();    }}<script type="text/javascript">    $(function () {        $("#btnSave").click(function () {            if ($("form").valid()) {                $.ajax({                url: "@Url.Action("CreateOpt")",                type: "Post",                data: $("form").serialize(),                dataType: "json",                success: function (data) {                    if (data.type == 1) {                        window.parent.frameReturnByMes(data.message);                        window.parent.frameReturnByReloadOpt(true);                        window.parent.frameReturnByClose()                    }                    else {                        window.parent.frameReturnByMes(data.message);                    }                }            });        }        return false;    });    $("#btnReturn").click(function () {        window.parent.frameReturnByClose();    });});</script><div class="mvctool bgb">@Html.ToolButton("btnSave", "icon-save", "保存", perm, "Save", true)@Html.ToolButton("btnReturn", "icon-return", "返回",false)</div>@using (Html.BeginForm()){             @Html.HiddenFor(model => model.Id) <table class="fromEditTable setTextWidth300">    <tbody>        <tr>            <td style="width:100px; text-align:right;">                @Html.LabelFor(model => model.Name):            </td>            <td style="width:310px">                @Html.EditorFor(model => model.Name)            </td>            <td>@Html.ValidationMessageFor(model => model.Name)</td>        </tr>        <tr>            <td style="width:100px; text-align:right;">                @Html.LabelFor(model => model.KeyCode):            </td>            <td style="width:310px">                @Html.EditorFor(model => model.KeyCode)            </td>            <td>@Html.ValidationMessageFor(model => model.KeyCode)</td>        </tr>        <tr>            <td style="width:100px; text-align:right;">                @Html.LabelFor(model => model.ModuleId):            </td>            <td style="width:310px">                @Html.TextBoxFor(model => model.ModuleId, new { @readOnly = "readOnly" })            </td>            <td>@Html.ValidationMessageFor(model => model.ModuleId)</td>        </tr>        <tr>            <td style="width:100px; text-align:right;">                @Html.LabelFor(model => model.IsValid):            </td>            <td style="width:310px">                @Html.CheckBoxFor(model => model.IsValid,  new { @checked = true })            </td>            <td>@Html.ValidationMessageFor(model => model.IsValid)</td>        </tr>        <tr>            <td style="width:100px; text-align:right;">                @Html.LabelFor(model => model.Sort):            </td>            <td style="width:310px">                @Html.EditorFor(model => model.Sort)            </td>            <td>@Html.ValidationMessageFor(model => model.Sort)</td>        </tr>    </tbody></table>}
CreateOpt.cshtml

创建模块的DAL层用到了一个存储过程,这个存储过程就是分配模块给角色的,要添加到EF

USE [AppDB]GO/****** Object:  StoredProcedure [dbo].[P_Sys_InsertSysRight]    Script Date: 12/24/2013 23:10:18 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCreate proc [dbo].[P_Sys_InsertSysRight]as--将设置好的模块分配到角色组    insert into SysRight(Id,ModuleId,RoleId,Rightflag)        select distinct b.Id+a.Id,a.Id,b.Id,0 from SysModule a,SysRole b        where a.Id+b.Id not in(select ModuleId+RoleId from SysRight)                            
P_Sys_InsertSysRight

 

后面补充一个存储过程,这个存储过程执行了清除无用的SysRightOperate(当每次删除角色或者模块,或者操作码时候会产生的垃圾),当然不清楚也不会对系统造成任何影响

Create proc [dbo].[P_Sys_ClearUnusedRightOperate]as--清理权限中的无用项目delete from SysRightOperate where Id not in(    select a.RoleId+a.ModuleId+b.KeyCode from SysRight a,SysModuleOperate b        where a.ModuleId = b.ModuleId)GO
P_Sys_ClearUnusedRightOperate

 最后大家别忘记要注入!!!一个丑陋的界面就这样完成了,大家自己动手美化一下吧.

本节演示了Easyui制作菜单,即无限级别树的做法,以及DataGrid之间的联动,我也是和大家一起学习,我也是Easyui的新手,如有不足,请大家见谅

阅读全文
0 0
原创粉丝点击