Skip to content

Commit

Permalink
在 ASP.Net Core 中添加或删除角色中的用户
Browse files Browse the repository at this point in the history
  • Loading branch information
ltm0203 committed Sep 17, 2019
1 parent 190ca14 commit 9c1f92b
Show file tree
Hide file tree
Showing 10 changed files with 569 additions and 9 deletions.
264 changes: 264 additions & 0 deletions StudentManagement/StudentManagement/Controllers/AdminController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,264 @@
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using StudentManagement.Models;
using StudentManagement.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace StudentManagement.Controllers
{
public class AdminController:Controller
{
private RoleManager<IdentityRole> roleManager;
private UserManager<ApplicationUser> userManager;

public AdminController(RoleManager<IdentityRole> roleManager,UserManager<ApplicationUser> userManager)
{
this.roleManager = roleManager;
this.userManager = userManager;
}



// GET Post

[HttpGet]
public IActionResult CreateRole()
{

return View();
}


[HttpPost]
public async Task<IActionResult> CreateRole(CreateRoleViewModel model)
{
if (ModelState.IsValid)
{

IdentityRole identityRole = new IdentityRole
{
Name = model.RoleName
};

//如果您尝试创建具有已存在的同名的角色,则会收到验证错误。
IdentityResult result = await roleManager.CreateAsync(identityRole);

if (result.Succeeded)
{
return RedirectToAction("ListRoles", "Admin");
}


foreach (var error in result.Errors)
{
ModelState.AddModelError("", error.Description);
}


}



return View(model);
}



public IActionResult ListRoles()
{

var roles = roleManager.Roles;

return View(roles);
}


[HttpGet]
public async Task<IActionResult> EditRole(string id)
{
var role = await roleManager.FindByIdAsync(id);
if (role == null)
{
ViewBag.ErrorMessage = $"角色id为{id}的信息不存在,请重试。";
return View("NotFound");
}

var model = new EditRoleViewModel
{
Id = role.Id,
RoleName = role.Name
};

var users = userManager.Users.ToList();
foreach (var user in users)
{
//如果用户拥有此角色,请将用户名添加到
//EditRoleViewModel模型中的Users属性中

if (await userManager.IsInRoleAsync(user,role.Name))
{
model.Users.Add(user.UserName);
}
}
//然后将对象传递给视图显示到客户端
return View(model);

}




[HttpPost]
public async Task<IActionResult> EditRole(EditRoleViewModel model)
{
var role =await roleManager.FindByIdAsync(model.Id);

if (role == null)
{
ViewBag.ErrorMessage = $"角色id为{model.Id}的信息不存在,请重试。";
return View("NotFound");
}
else
{
role.Name = model.RoleName;

var result= await roleManager.UpdateAsync(role);

if (result.Succeeded)
{
return RedirectToAction("ListRoles");
}

foreach (var error in result.Errors)
{

ModelState.AddModelError("", error.Description);

}


return View(model);

}







}


[HttpGet]
public async Task<IActionResult> EditUsersInRole(string roleId)
{
ViewBag.roleId = roleId;


var role = await roleManager.FindByIdAsync(roleId);

if (role == null)
{
ViewBag.ErrorMessage = $"角色id为{roleId}的信息不存在,请重试。";
return View("NotFound");
}

var model = new List<UserRoleViewModel>();


foreach (var user in userManager.Users)
{

var userRoleViewmodel = new UserRoleViewModel
{
UserId = user.Id,
UserName = user.UserName
};

if (await userManager.IsInRoleAsync(user, role.Name))
{
userRoleViewmodel.IsSelected = true;
}
else
{
userRoleViewmodel.IsSelected = false;

}


model.Add(userRoleViewmodel);

}



return View(model);

}

[HttpPost]
public async Task<IActionResult> EditUsersInRole(List<UserRoleViewModel> model, string roleId)
{

var role = await roleManager.FindByIdAsync(roleId);
if (role == null)
{
ViewBag.ErrorMessage = $"角色id为{roleId}的信息不存在,请重试。";
return View("NotFound");
}


for (int i = 0; i < model.Count; i++)
{
var user = await userManager.FindByIdAsync(model[i].UserId);

var isInRole = await userManager.IsInRoleAsync(user,role.Name);
IdentityResult result = null;

//被选中,不属于该角色,这个时候,添加到角色中。
if (model[i].IsSelected&&!isInRole)
{
result =await userManager.AddToRoleAsync(user,role.Name);
}
//没有被选中,但是用户已经在角色中,移除出来
else if (!model[i].IsSelected&&isInRole)
{
result =await userManager.RemoveFromRoleAsync(user,role.Name);
}
else//被选中,已经存角色中,不发生任何改变的数据
{
continue;//跳出当次循环
}

if (result.Succeeded)
{
//7个总用户数,0开始进行索引。
if (i<(model.Count-1))
{
continue;
}
else
{
return RedirectToAction("EditRole", new { id = roleId });

}


}



}

return RedirectToAction("EditRole", new { id = roleId });
}




}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using System.ComponentModel.DataAnnotations;

namespace StudentManagement.ViewModels
{
public class CreateRoleViewModel
{

[Required]
[Display(Name ="角色")]
public string RoleName { get; set; }

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace StudentManagement.ViewModels
{
public class EditRoleViewModel
{

public EditRoleViewModel()
{
Users = new List<string>();
}


[Display(Name ="角度Id")]
public string Id { get; set; }

[Required]
[Display(Name = "角色名称")]
public string RoleName { get; set; }


public List<string> Users { get; set; }


}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace StudentManagement.ViewModels
{
public class UserRoleViewModel
{
public string UserId { get; set; }

public string UserName { get; set; }

public bool IsSelected { get; set; }


}
}
34 changes: 34 additions & 0 deletions StudentManagement/StudentManagement/Views/Admin/CreateRole.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
@model CreateRoleViewModel

@{
ViewBag.Title = "创建角色";
}



<form asp-action="CreateRole" method="post" class="mt-3">

<div asp-validation-summary="All" class="text-danger"></div>

<div class="form-group row">

<label asp-for="RoleName" class="col-sm-2 col-form-label "></label>
<div class="col-sm-10">
<input asp-for="RoleName" class=" form-control" placeholder="请输入角色名称" />
<span asp-validation-for="RoleName" class="text-danger"></span>

</div>
</div>
<div class="form-group row">


<div class="col-sm-10">

<button type="submit" class="btn btn-primary" style="width:auto" >创建角色</button>

</div>
</div>



</form>
Loading

0 comments on commit 9c1f92b

Please sign in to comment.