篇(14)-Asp.Net Core入门实战-权限管理之角色编辑和赋权(ViewModel-DTO初探)

入门实战-权限管理之角色编辑和赋权(ViewModel-DTO初探)

前面几章讲了菜单功能的管理之后,我们再创建一个角色管理的功能,创建过程不再详细介绍,只要按照菜单管理功能的步骤进行创建即可;和前面讲的稍微不同的是,现在多了一个Service层和异步操作,功能处理的代码放在这个层完成,只在Controller中调用即可。

一、再讲角色的操作之前,我们先聊一个概念:ViewModel,或者叫DTO;两个是一个意思,叫法不一样而已。ViewModel是ASP.NET MVC应用中的隐式声明的层,用来维护Model和View之间的数据传递, 因此,ViewModel也简称为数据传输对象或 DTO。

我们举个简单的例子:我先以原来Menu菜单功能中的一个查看菜单明细Details来举例说明。

(1):其View代码(Details.cshtml)如下

(2):其Controller的Details Action代码如下:

(3):其预览效果为:

Controller传递到View视图的数据是item,并还定了一个ViewBag.PageTitle的数据,我想把ViewBag.PageTitle个跟随Model item一并传递到View,而且不用ViewBag的方式,那么我就新建一个ViewModel类型的Model,叫MenuView,它的代码是这样:

在Controller中改如何获取值:

在View中如何显示值:

以上就是一个ViewModel的简单应用例子,很好理解。

二、在接着说角色功能的例子,简单说下过程

1.创建角色数据表ManagerRole;

CREATE TABLE [dbo].[ManagerRole](
[Id] [int] IDENTITY(1,1) NOT NULL,
[RoleName] [varchar](64) NOT NULL,
[RoleType] [int] NOT NULL,
[IsSystem] [bit] NOT NULL,
[AddManagerId] [int] NOT NULL,
[AddTime] [datetime] NOT NULL,
[ModifyManagerId] [int] NULL,
[ModifyTime] [datetime] NULL,
[IsDelete] [bit] NOT NULL,
[Remark] [varchar](128) NULL,
CONSTRAINT [PK_MANAGERROLE] PRIMARY KEY NONCLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

 

2.编写角色Model,ManagerRole;

public class ManagerRole
{
/// <summary>
/// 主键
/// </summary>
[Key]
public int Id { get; set; }
/// <summary>
/// 角色名称
/// </summary>
[Required]
public String RoleName { get; set; }
/// <summary>
/// 角色类型1超管2系管
/// </summary>
[Required]
public int RoleType { get; set; }
/// <summary>
/// 是否系统默认
/// </summary>
[Required]
public Boolean IsSystem { get; set; }
/// <summary>
/// 添加人
/// </summary>
public int AddManagerId { get; set; }
/// <summary>
/// 添加时间
/// </summary>
public DateTime AddTime { get; set; }
/// <summary>
/// 修改人
/// </summary>
public int? ModifyManagerId { get; set; }
/// <summary>
/// 修改时间
/// </summary>
public DateTime? ModifyTime { get; set; }
/// <summary>
/// 是否删除
/// </summary>
public Boolean IsDelete { get; set; }
/// <summary>
/// 备注
/// </summary>

public String Remark { get; set; }

 

3.编写角色Controller[ManagerRoleController.cs]和View;

(3.1)Index.cshtml的View视图代码

@using RjWebCms.Db;
@model PaginatedList<ManagerRole>
@{
ViewData["Title"] = "角色列表";
}
@section Scripts{
<script type="text/javascript">
$(document).ready(function () {
$("a[name='DelAll']").click(function (){
DelAll();
});
});
function DelAll() {
var ids = document.getElementsByName("chk_ids");
var arrIds = "";
var n = 0;
for (var i = 0; i < ids.length; i++)
{
if (ids[i].checked == true) {
arrIds += ids[i].value + ",";
n++;
}
}

if (n == 0) {
alert("请选择要删除的信息");
return;
}

arrIds = arrIds.substr(0, arrIds.length - 1);
$.ajax({
type: "POST",
url: "/ManagerRole/DeleteAll",
data: { idString: arrIds },
beforeSend: function (xhr) {
xhr.setRequestHeader("RequestVerificationToken",
$('input:hidden[name="__RequestVerificationToken"]').val());
},

success: function (res) {
alert('删除成功!');
window.location.href = "/ManagerRole/Index";
},
failure: function (data, error) {
alert('删除失败');
}
});
}

function del() {
$.ajax({
type: "POST",
url: "/ManagerRole/Details",
data: {id:8},
beforeSend: function (xhr) {
xhr.setRequestHeader("RequestVerificationToken",
$('input:hidden[name="__RequestVerificationToken"]').val());
},

success: function (response) {
alert('OK');
alert(response);
},

failure: function (response) {
alert(response);
}
});
}
</script>
}
<div class="panel panel-default todo-panel">
<div class="panel-heading">@ViewData["Title"]</div>
@Html.AntiForgeryToken()
<form asp-action="Index" method="get">
<table>
<tr><td><a asp-controller="ManagerRole" asp-action="Create">添加</a></td></tr>
<tr>
<td>查询关键词:<input type="text" name="SearchString" value="@ViewData["CurrentFilter"]" /></td>
<td><input type="submit" value="查询" /></td>
<td><a asp-action="Index">Back</a></td>
<td><a id="DelAll" name="DelAll">批量删除</a></td>
</tr>
</table>
</form>
<table class="table table-hover">
<thead>
<tr>
<td>&#x2714;</td>
<td><a asp-action="Index" asp-route-sortOrder="@ViewData["NameSortParm"]" asp-route-currentFilter="@ViewData["CurrentFilter"]">角色名称</a></td>
<td>角色类型</td>
<td><a asp-action="Index" asp-route-sortOrder="@ViewData["DateSortParm"]" asp-route-currentFilter="@ViewData["CurrentFilter"]">时间</a></td>
<td>操作</td>
</tr>
@foreach (var item in Model)
{
<tr>
<td><input type="checkbox" class="done-checkbox" name="chk_ids" value="@item.Id"></td>
<td>@item.RoleName</td>
<td>@item.RoleType</td>
<td>@item.AddTime</td>
<td>
<a asp-controller="ManagerRole" asp-action="Details" asp-route-id="@item.Id">View</a>
<a asp-action="Edit" asp-route-id="@item.Id">Edit</a>
<a asp-controller="RolePermission" asp-action="Index" asp-route-id="@item.Id">Menu</a>
<a asp-controller="ManagerRole" asp-action="Delete" asp-route-id="@item.Id">Delete</a>
</td>
</tr>
}
</thead>
</table>
@{
var prevDisabled = !Model.HasPreviousPage ? "disabled" : "";
var nextDisabled = !Model.HasNextPage ? "disabled" : ""; ;
}
<a asp-action="Index"
asp-route-sortOrder="@ViewData["CurrentSort"]"
asp-route-pageNumber="@(Model.PageIndex - 1)"
asp-route-currentFilter="@ViewData["CurrentFilter"]"
class="btn btn-default @prevDisabled">
上一页
</a>
<a asp-action="Index"
asp-route-sortOrder="@ViewData["CurrentSort"]"
asp-route-pageNumber="@(Model.PageIndex + 1)"
asp-route-currentFilter="@ViewData["CurrentFilter"]"
class="btn btn-default @nextDisabled">
下一页
</a>
<div class="panel-footer add-item-form">
<!-- TODO: Add item form -->
</div>
</div>

 

(3.2)Create.cshtml视图代码

@{ ViewData["Title"] = "新建角色"; }
@model ManagerRole
<form action="/ManagerRole/Create" method="post">
@Html.AntiForgeryToken()
<div>
<label asp-for="RoleName">角色名称</label>
<div>
<input type="text" asp-for="RoleName" name="RoleName" placeholder="请输入角色名称">
</div>
</div>
<div>
<label asp-for="RoleType">角色类型</label>
<div>
<select name="RoleType" class="RoleType">
<option value="1">超级管理员</option>
<option value="2" selected>系统管理员</option>
</select>
</div>
</div>
<div>
<label asp-for="IsSystem">系统默认</label>
<div>
<select asp-for="IsSystem" name="IsSystem" class="IsSystem">
<option value="False" selected></option>
<option value="True"></option>
</select>
</div>
</div>
<div>
<label asp-for="Remark">备注</label>
<div>
<textarea placeholder="请输入备注信息" asp-for="Remark" name="Remark"></textarea>
</div>
</div>
<div>
<div>
<button type="submit">确定</button>
<button type="reset">重置</button>
</div>
</div>
</form>

 

(3.3)Edit.cshtml视图代码

@{ ViewData["Title"] = "角色编辑"; }
@model ManagerRole
<form action="/ManagerRole/Edit" method="post">
@Html.AntiForgeryToken()
<input type="hidden" asp-for="Id" />
<div>
<label asp-for="RoleName">角色名称</label>
<div>
<input type="text" asp-for="RoleName" name="RoleName" class="layui-input RoleName" lay-verify="required" placeholder="请输入角色名称">
</div>
</div>
<div>
<label asp-for="RoleType">角色类型</label>
<div>
<select name="RoleType" class="RoleType">
<option value="1" selected="@(Model.RoleType == 1 ? " selected" : null)">超级管理员</option>
<option value="2" selected="@(Model.RoleType == 2 ? " selected" : null)">系统管理员</option>
</select>
</div>
</div>
<div>
<label asp-for="IsSystem">系统默认</label>
<div>
<select asp-for="IsSystem" name="IsSystem" class="IsSystem">
<option value="false" selected="@(Model.IsSystem==false ? " selected" : null)"></option>
<option value="true" selected="@(Model.IsSystem==true ? " selected" : null)"></option>
</select>
</div>
</div>
<div>
<label asp-for="Remark">备注</label>
<div>
<textarea placeholder="请输入备注信息" asp-for="Remark" name="Remark" class="layui-textarea Remark"></textarea>
</div>
</div>
<div>
<div>
<button type="submit">确定</button>
<button type="reset">重置</button>
</div>
</div>
</form>

 

(3.4)ManagerController.cs控制器代码如下,注意各个Action的类型声明,在Index这个Action上,我加了个[Authorize]声明,意思是,如果你要查看角色,必须是登录用户才行。

public class ManagerRoleController : Controller
{
private readonly IManagerRoleService _roleService;
private readonly AppDbContext _appDbContext;
public ManagerRoleController(IManagerRoleService roleService, AppDbContext appDbContext)
{
_roleService = roleService;
_appDbContext = appDbContext;
}

[Authorize]
public async Task<IActionResult> Index(string sortOrder,string currentFilter,string searchString,int? pageNumber)
{
ViewData["CurrentSort"] = sortOrder;
ViewData["NameSortParm"] = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
ViewData["DateSortParm"] = sortOrder == "Date" ? "date_desc" : "Date";
if (searchString != null)
{
pageNumber = 1;
}
else
{
searchString = currentFilter;
}
ViewData["CurrentFilter"] = searchString;
var mRoles = from s in _appDbContext.ManagerRole
select s;
if (!string.IsNullOrEmpty(searchString))
{
mRoles = mRoles.Where(s => s.RoleName.Contains(searchString));
}

switch (sortOrder)
{
case "name_desc":
mRoles = mRoles.OrderByDescending(s => s.RoleName);
break;
case "Date":
mRoles = mRoles.OrderBy(s => s.AddTime);
break;
case "date_desc":
mRoles = mRoles.OrderByDescending(s => s.AddTime);
break;
default:
mRoles = mRoles.OrderBy(s => s.RoleName);
break;
}

int pageSize = 4;
return View(await PaginatedList<ManagerRole>.CreateAsync(mRoles.AsNoTracking(), pageNumber ?? 1, pageSize));
}

[HttpGet]
public IActionResult Create()
{
return View();
}

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(ManagerRole mRole)
{
//去掉对字段IsSystem的验证,IsSystem在数据库是bool类型,而前端是0和1,ModelState的验证总是报false,所以去掉对其验证
//ModelState.Remove("IsSystem");//在View端已经解决了了bool类型,那么此行代码可以不用
if (ModelState.IsValid)
{
var successful = await _roleService.AddManagerRoleAysnc(mRole);
if (successful)
return RedirectToAction("RoleList");
else
return BadRequest("失败");
}
return View(mRole);
}

[HttpGet]
public async Task<IActionResult> Edit(int id)
{
if (string.IsNullOrEmpty(id.ToString()))
return NotFound();
var mRole = await _roleService.FindManagerRoleAsync(id);
if (mRole == null)
return NotFound();
return View(mRole);
}

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id,ManagerRole mRole)
{
if (id != mRole.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
var result = await _roleService.UpdateManagerRoleAsync(id,mRole);
}
catch (Exception ex)
{
return BadRequest("编辑失败");
}
return RedirectToAction("Index");
}
return View(mRole);
}

[HttpGet]
public async Task<IActionResult> Delete(int id)
{
var result = await _roleService.DeleteManagerRoleAsync(id);
if (result)
return RedirectToAction("Index");
else
return BadRequest("删除失败");
}

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteAll(string idString)
{
int countSuccessDel = 0;//记录删除成功的数据条数
int countFailedDel = 0;//记录删除成功的数据条数
if (idString.Length > 0)
{
if (idString.IndexOf(',') > 0)
{
string[] ids = idString.Split(',');
foreach (string id in ids)
{
var result = await _roleService.DeleteManagerRoleAsync(int.Parse(id));
if(result)
countSuccessDel++;
else
countFailedDel++;
}
if (countSuccessDel > 0)
return RedirectToAction("Index");
else
return BadRequest("删除失败");
}
}
return BadRequest("失败");
}

[HttpGet]
public async Task<IActionResult> Details(int id)
{
if (string.IsNullOrEmpty(id.ToString()))
return NotFound();
var mRole = await _roleService.FindManagerRoleAsync(id);
if (mRole == null)
return NotFound();
return View(mRole);
}
}

 

(3.5)给角色赋权菜单

在列表页,也就是Index的Action内对其进行分页和添加相关的增、删、改、查的按钮,列表页多一个设置菜单的按钮(Menu),点击Menu按钮的目的是为了给这个角色赋予菜单的权限,这是权限管理控制到菜单级别的一种处理方式。

我在菜单列表页(Index.cshtml)中Menu的链接我是这样写的如下图:

链接到新的Controller和对应的Action:RolePermission是表[RolePermission]对应的Controller,它存储了角色Id与菜单Id的关系;

一个角色如何设置和编辑其具有哪些菜单的页面视图如下:

(3.6)上面设置角色菜单的这个页面的View代码如下(从这里开始那么涉及到了ViewModel的功能),可以看@model指令,我引入了一个MenuView,这是一个ViewModel类型,因为需要集合数据,单纯的一个Menu无法满足我的数据显示和操作,看完View代码,请注意对应的Controller代码:

@model MenuView
@{
ViewData["Title"] = "设置角色的权限菜单";
}
@section Scripts{
<script type="text/javascript" src="~/js/jquery-3.6.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#btnSave").click(function () {
SetCheckBoxSelected();
});
});
function SetCheckBoxSelected() {
var ids = document.getElementsByName("Cbox_H");
var arrIds = "";
var n = 0;
for (var i = 0; i < ids.length; i++) {
if (ids[i].checked == true) {
arrIds += ids[i].value + ",";
n++;
}
}
if (n == 0) {
alert("请选择要设置的权限菜单");
return;
}
arrIds = arrIds.substr(0, arrIds.length - 1);//选择的菜单id集合
var roleId = document.getElementById("hidden_roleid").value; //角色id
$.ajax({
type: "POST",
url: "/RolePermission/Edit",
data: { idString: arrIds, roleid: roleId },
beforeSend: function (xhr) {
xhr.setRequestHeader("RequestVerificationToken",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function (res) {
alert('设置成功!');
//window.location.href = "/RolePermission/Index";
},
failure: function (data, error) {
alert('删除失败');
}
});
}
</script>
}

<div class="panel panel-default todo-panel">
<div class="panel-heading">@ViewData["Title"]</div>
@Html.AntiForgeryToken()
<div>
当前角色:<label id="lab_rolename">@ViewData["roleName"]</label>
<button type="button" id="btnSave">保存</button>
<input type="hidden" id="hidden_roleid" value="@ViewData["roleId"]"/>
</div>

<table class="table table-hover">
<thead>
<tr>
<td>系统类别</td>
<td>菜单名称</td>
</tr>
@foreach (var item in Model.MenuList)
{
if (item.ParentId == 0)
{
<tr>
<td>
<input type="checkbox" name="Cbox_H" value="@item.Id"
@(Html.Raw(Model.MenuIds.Contains(item.Id)? "checked=\"checked\"" : "")) />
@item.DisplayName
&nbsp;
</td>
<td>&nbsp;</td>
</tr>
}
else
{
<tr>
<td>&nbsp;</td>
<td>
<input type="checkbox" name="Cbox_H" value="@item.Id"
@(Html.Raw(Model.MenuIds.Contains(item.Id) ? "checked=\"checked\"" : "")) />
@item.DisplayName
</td>
</tr>
}
}
</thead>
</table>
<div class="panel-footer add-item-form">
<!-- TODO: Add item form -->
</div>
</div>

 

这里着重理解一下代码:<input type="checkbox" name="Cbox_H" value="@item.Id"

@(Html.Raw(Model.MenuIds.Contains(item.Id) ? "checked=\"checked\"" : "")) />

就是复选框赋值问题:通过三元运算,判断当前RoleId下有这个MenuId,则选中复选框,没有这个MenuId,就置空。

简单说下处理逻辑:

(1).视图页面将列出所有菜单名称(带复选框);点开本页就只有一种操作-编辑;

(2).编辑时,需要先将原有选择保存过的显示勾选上,然后可再勾选编辑保存;

 

(3.7)权限勾选菜单设置的Controller操作代码,

3.7.1 先看MenuView代码

3.7.2再看RolePermissionController.cs的代码

public class RolePermissionController : Controller
{
private readonly IRolePermissionService _rolePermissionService;
private readonly IManagerRoleService _managerRoleService;
private readonly IMenuService _menuService;
private readonly AppDbContext _appDbContext;
public RolePermissionController(IRolePermissionService rolePermissionService, IManagerRoleService managerRoleService,IMenuService menService,AppDbContext appDbContext)
{
_rolePermissionService = rolePermissionService;
_managerRoleService = managerRoleService;
_menuService = menService;
_appDbContext = appDbContext;
}

public async Task<IActionResult> IndexAsync(int id)
{
ViewData["roleId"] = id;
var ManagerRole = await _managerRoleService.FindManagerRoleAsync(id);
if (ManagerRole != null)
ViewData["roleName"] = ManagerRole.RoleName;
else
ViewData["roleName"] = "未知角色";
#region 查出已经分派权限的roleId 对应的MenuId 参数id=角色id
List<int> menuIds = new List<int>();
menuIds.Add(-1);
if (!string.IsNullOrEmpty(id.ToString()))
{
var rolepermissions = await _rolePermissionService.GetRolePermissionAsync(id);
foreach (RolePermission rp in rolepermissions)
{
menuIds.Add(rp.MenuId);
}
}
#endregion
#region 绑定前台CheckBox
var items = await _menuService.GetMenusByParentId(0);
List<Menu> lists = new List<Menu>();
List<RolePermission> listRolePermission = new List<RolePermission>();
foreach (Menu m in items)
{
lists.Add(m);
var items2 = await _menuService.GetMenusByParentId(m.Id);
foreach (Menu mu in items2)
{
lists.Add(mu);
}
}
var model = new MenuView()
{
MenuList = lists,
MenuIds = menuIds
};
return View(model);
#endregion
}

public async Task<IActionResult> EditAsync(int roleid,string idString)
{
string Msg = "保存成功";
#region 先删除旧的
await _rolePermissionService.DeleteRolePermissionByRoleId(roleid);
#endregion
#region 再添加新的
if (idString.Length > 0)
{
if (idString.IndexOf(',') > 0)
{
string[] ids = idString.Split(',');
List<RolePermission> rps = new List<RolePermission>();
foreach (string id in ids)
{
RolePermission rp = new RolePermission();
rp.RoleId = roleid;
rp.MenuId = int.Parse(id);
rps.Add(rp);
}
await _rolePermissionService.AddRolePermissionAsync(rps);
}
}
#endregion
return View(Msg);
}
}

 

代码折叠起来读,就很好理解了。关于return View(Msg),这是个简单处理,以后将统一返回Json或标准信息时,在详细讲解,你可以做这个Action转向,或Return Ok();

(3.8)其中RolePermission对应的Service代码如下:

public class RolePermissionService : IRolePermissionService
{
private readonly AppDbContext _appDbContext;
public RolePermissionService(AppDbContext appDbContext)
{
_appDbContext = appDbContext;
}

public async Task<bool> AddRolePermissionAsync(RolePermission rolePermission)
{
await _appDbContext.RolePermission.AddAsync(rolePermission);
var result = await _appDbContext.SaveChangesAsync();
return result == 1;
}

public async Task<bool> AddRolePermissionAsync(List<RolePermission> rps)
{
await _appDbContext.RolePermission.AddRangeAsync(rps);
var result = await _appDbContext.SaveChangesAsync();
return result == 1;
}
public async Task<bool> DeleteRolePermissionAsync(int Id)
{
var delRolePermission = await _appDbContext.RolePermission.FirstOrDefaultAsync(x => x.Id == Id);
if (delRolePermission != null)
{
_appDbContext.RolePermission.Remove(delRolePermission);
}
var result = await _appDbContext.SaveChangesAsync();
return result == 1; //注意(result==1 如果等式成立,则返回true,说明删除成功)
}
public async Task<bool> DeleteRolePermissionByRoleId(int roleId)
{
List<RolePermission> delRolePermissions = await _appDbContext.RolePermission.Where(x => x.RoleId == roleId).ToListAsync();
if (delRolePermissions != null)
{
foreach(RolePermission rp in delRolePermissions)
_appDbContext.RolePermission.Remove(rp);
}

var result = await _appDbContext.SaveChangesAsync();
return result == 1; //注意(result==1 如果等式成立,则返回true,说明删除成功)
}

/// <summary>
/// 查看一个角色与菜单ID对应关系
/// </summary>
/// <param name="Id"></param>
/// <returns></returns>
public async Task<RolePermission> FindRolePermissionAsync(int Id)
{
var item = await _appDbContext.RolePermission.Where(x => x.Id == Id).FirstOrDefaultAsync();
return item;
}

/// <summary>
/// 获取所有角色和菜单
/// </summary>
/// <returns></returns>
public async Task<RolePermission[]> GetRolePermissionAsync()
{
var items = await _appDbContext.RolePermission.ToArrayAsync();
return items;
}
/// <summary>
/// 获取一个角色的所有菜单
/// </summary>
/// <param name="roleId"></param>
/// <returns></returns>
public async Task<RolePermission[]> GetRolePermissionAsync(int roleId)
{
var items = await _appDbContext.RolePermission.Where(x => x.RoleId == roleId).ToArrayAsync();
return items;
}

/// <summary>
/// 更新角色权限
/// </summary>
/// <param name="id"></param>
/// <param name="rolePermission"></param>
/// <returns></returns>

public async Task<bool> UpdateRolePermissionAsync(int id, RolePermission rolePermission)
{
var oldRolePermission = await FindRolePermissionAsync(id); //找出旧对象
//将新值赋到旧对象上
oldRolePermission.MenuId = rolePermission.MenuId;
oldRolePermission.RoleId = rolePermission.RoleId;
oldRolePermission.Permission = rolePermission.Permission;
//对旧对象执行更新
_appDbContext.Entry(oldRolePermission).State = EntityState.Modified;
var result = await _appDbContext.SaveChangesAsync();
return result == 1;
}

}

 

注意有批量添加的功能,读代码时可稍加留意。

posted @ 2022-11-19 14:55  荣景智工  阅读(494)  评论(0编辑  收藏  举报