zoukankan      html  css  js  c++  java
  • mvc core2.1 Identity.EntityFramework Core ROle和用户绑定查看 (八)完成

    添加角色属性查看

    Views ->Shared->_Layout.cshtml

    <div class="navbar-collapse collapse">
    <ul class="nav navbar-nav">
      <li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li>
      <li><a asp-area="" asp-controller="Home" asp-action="About">About</a></li>
      <li><a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a></li>
      <li><a asp-area="" asp-controller="Account" asp-action="Index">Account</a></li>
      <li><a asp-area="" asp-controller="Claims" asp-action="Index">Claims</a></li>  
      <li><a asp-area="" asp-controller="Role" asp-action="Index">Role</a></li>   //加这句

    Controllers ->RoleController.cs 新建

      1 using System;
      2 using System.Collections.Generic;
      3 using System.Diagnostics;
      4 using System.Linq;
      5 using System.Threading.Tasks;
      6 using Microsoft.AspNetCore.Mvc;
      7 using IdentityMvc.Models;
      8 using Microsoft.AspNetCore.Identity;
      9 using Microsoft.AspNetCore.Authorization;
     10 using IdentityMvc.Models.AccountViewModels;
     11 using Microsoft.AspNetCore.Authentication;
     12 using System.ComponentModel.DataAnnotations;
     13 using Microsoft.EntityFrameworkCore;
     14 using IdentityMvc.Models.RoleViewModels;
     15 using System.Security.Claims;
     16 
     17 namespace IdentityMvc.Controllers
     18 {
     19     [Authorize]
     20     public class RoleController : Controller
     21     {
     22         private readonly UserManager<ApplicationUser> _userManager;
     23         private readonly RoleManager<ApplicationRole> _roleManager;
     24        
     25         public RoleController(UserManager<ApplicationUser> userManager,
     26             RoleManager<ApplicationRole> roleManager)
     27         {
     28             _roleManager = roleManager;
     29             _userManager = userManager;
     30         }
     31         [TempData]
     32         public string ErrorMessage { get; set; }
     33 
     34         [HttpGet]
     35         public ActionResult Index() {
     36 
     37             var dd = _roleManager.Roles.Include(d => d.UserRoles).Select(o => new
     38             {
     39                 o.Id,
     40                 o.Name,
     41                 userlist = o.UserRoles.Select(t => t.UserId).ToList(),
     42             }).Select(t => new {t.Id,t.Name,
     43                 useridlist = string.Join(",", t.userlist)
     44             });
     45             List<RoleViewModels> list = new List<RoleViewModels>();
     46 
     47             foreach (var gg in dd)
     48             {
     49                 var pp = _userManager.Users.Where(o => gg.useridlist.Contains(o.Id)).Select(o => o.UserName).ToList();
     50 
     51                 list.Add( new RoleViewModels { Id= gg.Id,Role=gg.Name, Name = string.Join(",", pp) });
     52                 
     53             }
     54         
     55             return View(list);
     56             // return View(_roleManager.Roles.Include(d => d.UserRoles));
     57         }
     58 
     59         [HttpGet]
     60         public ActionResult Create() {
     61             return View();
     62         }
     63 
     64         [HttpPost]
     65         public async Task<ActionResult> Create(RoleViewModels model)
     66          {
     67             if (ModelState.IsValid) {
     68                  IdentityResult result = await _roleManager.CreateAsync(new ApplicationRole{Name=model.Name});
     69                 if (result.Succeeded) {
     70 
     71                     var officeClaim = new Claim("office", model.OfficeNumber.ToString(), ClaimValueTypes.String);
     72                     await _roleManager.AddClaimAsync(await _roleManager.FindByNameAsync(model.Name), officeClaim);
     73 
     74                     return RedirectToAction("Index");
     75                 } else {
     76                     AddErrors(result);
     77                 }
     78             }
     79             return View(model);
     80         }
     81 
     82         [HttpPost]
     83         public async Task<ActionResult> Delete(string id) {
     84             ApplicationRole role = await _roleManager.FindByIdAsync(id);
     85             if (role != null) {
     86                 IdentityResult result = await _roleManager.DeleteAsync(role);
     87                 if (result.Succeeded) {
     88                     return RedirectToAction("Index");
     89                 } else {
     90                     return View("Error", result.Errors);
     91                 }
     92             } else {
     93                 return View("Error", new string[] { "Role Not Found" });
     94             }
     95         }
     96 
     97          public async Task<ActionResult> Edit(string id) {
     98             ApplicationRole role = await _roleManager.FindByIdAsync(id);
     99              var temp = _roleManager.Roles.Include(d => d.UserRoles).Where(d => d.Id == id)
    100                .Select(d => new
    101                {
    102                    d.UserRoles
    103                }).ToArray();
    104             string[] memberID = temp[0].UserRoles.Select(x => x.UserId).ToArray();
    105             var  members = _userManager.Users.Where(x => memberID.Any(y => y == x.Id));
    106             var nonMembers = _userManager.Users.Except(members);
    107             
    108             return View(new RoleEditModel {
    109                 Role = role,
    110                 Members = members,
    111                 NonMembers = nonMembers
    112             });
    113         }
    114 
    115         [HttpPost]
    116         public async Task<ActionResult> Edit(RoleModificationModel model) {
    117             IdentityResult result;
    118             if (ModelState.IsValid) {
    119                 foreach (string userId in model.IdsToAdd ?? new string[] { }) {
    120                     result = await _userManager.AddToRoleAsync(await _userManager.FindByIdAsync(userId), model.RoleName);
    121                     if (!result.Succeeded) {
    122                         return View("Error", result.Errors);
    123                     }
    124                 }
    125                 foreach (string userId in model.IdsToDelete ?? new string[] { }) {
    126                      result = await _userManager.RemoveFromRoleAsync(await _userManager.FindByIdAsync(userId),
    127                         model.RoleName);
    128                      if (!result.Succeeded) {
    129                         return View("Error", result.Errors);
    130                     }
    131                 }
    132                 return RedirectToAction("Index");
    133             }
    134             return View("Error", new string[] { "Role Not Found" });
    135         }
    136 
    137         private void AddErrors(IdentityResult result)
    138         {
    139             foreach (var error in result.Errors)
    140             {
    141                 ModelState.AddModelError(string.Empty, error.Description);
    142             }
    143         }
    144     }
    145 }
    View Code

    Models->RoleViewModels->RoleViewModels.cs 新建

     1 using System;
     2 using System.Collections.Generic;
     3 using System.ComponentModel.DataAnnotations;
     4 using System.Linq;
     5 using System.Threading.Tasks;
     6 
     7 namespace IdentityMvc.Models.RoleViewModels
     8 {
     9     public class RoleViewModels
    10     {
    11         public string Id { get; set; }
    12 
    13         public string Name { get; set; }
    14 
    15         public string Role { get; set; }
    16 
    17         public string OfficeNumber { get; set; }
    18     }
    19       public class RoleEditModel 
    20     {
    21         public ApplicationRole Role { get; set; }
    22         public IEnumerable<ApplicationUser> Members { get; set; }
    23         public IEnumerable<ApplicationUser> NonMembers { get; set; }
    24     }
    25     public class RoleModificationModel {
    26         [Required]
    27         public string RoleName { get; set; }
    28         public string[] IdsToAdd { get; set; }
    29         public string[] IdsToDelete { get; set; }
    30     }
    31 }
    View Code

    Views->Role->Create.cshtml 

     1 @model RoleViewModels
     2 @{ ViewBag.Title = "Create Role";}
     3 <h2>Create Role</h2>
     4 @Html.ValidationSummary(false)
     5 @using (Html.BeginForm()) {
     6     <div class="form-group">
     7                 <label asp-for="Name" class="control-label"></label>
     8                 <input asp-for="Name" class="form-control" />
     9                 <span asp-validation-for="Name" class="text-danger"></span>
    10             </div>
    11     <div class="form-group">
    12                 <label asp-for="OfficeNumber" class="control-label"></label>
    13                 <input asp-for="OfficeNumber" class="form-control" />
    14                 <span asp-validation-for="OfficeNumber" class="text-danger"></span>
    15             </div>
    16 
    17     <button type="submit" class="btn btn-primary">Create</button>
    18     @Html.ActionLink("Cancel", "Index", null, new { @class = "btn btn-default" })
    19 }
    View Code

    Views->Role->Edit.cshtml 

     1 @model RoleEditModel
     2 @{ ViewBag.Title = "Edit Role";}
     3 @Html.ValidationSummary()
     4 @using (Html.BeginForm()) {
     5     <input type="hidden" name="roleName" value="@Model.Role.Name" />
     6     <div class="panel panel-primary">
     7         <div class="panel-heading">Add To @Model.Role.Name</div>
     8         <table class="table table-striped">
     9             @if (Model.NonMembers == null) {
    10                 <tr><td colspan="2">All Users Are Members</td></tr>
    11             } else {
    12                 <tr><td>User ID</td><td>Add To Role</td></tr>
    13                 foreach (ApplicationUser user in Model.NonMembers) {
    14                     <tr>
    15                         <td>@user.UserName</td>
    16                         <td>
    17                             <input type="checkbox" name="IdsToAdd" value="@user.Id">
    18                         </td>
    19                     </tr>
    20                 }
    21             }
    22         </table>
    23     </div>
    24     <div class="panel panel-primary">
    25         <div class="panel-heading">Remove from @Model.Role.Name</div>
    26         <table class="table table-striped">
    27             @if (Model.Members == null) {
    28                 <tr><td colspan="2">No Users Are Members</td></tr>
    29             } else {
    30                 <tr><td>User ID</td><td>Remove From Role</td></tr>
    31                 foreach (ApplicationUser user in Model.Members) {
    32                     <tr>
    33                         <td>@user.UserName</td>
    34                         <td>
    35                             <input type="checkbox" name="IdsToDelete" value="@user.Id">
    36                         </td>
    37                     </tr>
    38                 }
    39             }
    40         </table>
    41     </div>
    42     <button type="submit" class="btn btn-primary">Save</button>
    43     @Html.ActionLink("Cancel", "Index", null, new { @class = "btn btn-default" })
    44 }
    View Code

    Views->Role->Index.cshtml 

     1 @model IEnumerable<RoleViewModels>
     2 @using IdentityMvc.App_Code
     3 @{ ViewBag.Title = "Roles"; }
     4 
     5 <div class="panel panel-primary">
     6     <div class="panel-heading">Roles</div>
     7     <table class="table table-striped"> 
     8 
     9         <tr><th>ID</th><th>Name</th><th>Users</th><th></th></tr>
    10         @if (Model.Count() == 0) {
    11             <tr><td colspan="4" class="text-center">No Roles</td></tr>
    12         } else {
    13             foreach (RoleViewModels role in Model) {
    14                 <tr>
    15                     <td>@role.Id</td>
    16                     <td>@role.Role</td>
    17                     <td>@role.Name
    18                     </td>
    19                     <td>
    20                         @using (Html.BeginForm("Delete", "Role",
    21                             new { id = role.Id })) {
    22                             @Html.ActionLink("Edit", "Edit", new { id = role.Id },
    23                                      new { @class = "btn btn-primary btn-xs" })
    24                             <button class="btn btn-danger btn-xs"
    25                                     type="submit">
    26                                 Delete
    27                             </button>
    28                         }
    29                     </td>
    30                 </tr>
    31             }
    32         }
    33     </table>
    34 </div>
    35 @Html.ActionLink("Create", "Create", null, new { @class = "btn btn-primary" })  
    View Code

    Startup.cs->ConfigureServices

    services.AddIdentity<ApplicationUser, IdentityRole>() ->   services.AddIdentity<ApplicationUser, ApplicationRole>()
  • 相关阅读:
    2021杭电多校4 1003/HDU 6987 Cycle Binary
    2021牛客多校5 G/nowcoder 11256 G Greater Integer, Better LCM
    2021牛客多校4 G/nowcoder 11255 G Product
    2021牛客多校4 H/nowcoder 11255 H Convolution
    FFT/NTT字符串模糊匹配
    Codeforces Harbour.Space Scholarship Contest 2021-2022 (open for everyone, rated, Div. 1 + Div. 2)
    2021杭电多校2 1006/HDU 6966 I love sequences
    2021牛客多校3 E/nowcoder 11254 E Math
    2021杭电多校1 1011/HDU 6960 Necklace of Beads
    linux操作系统使用小技巧,把程序和数据彻底分开
  • 原文地址:https://www.cnblogs.com/LiuFengH/p/9556533.html
Copyright © 2011-2022 走看看