【从实作学习ASP.NET Core】Day17 | 後台 | 角色的 CRUD 页面

昨天在处理角色的时候已经把新增的页面处理好了
今天就用之前的方法把角色的其他页面也建立起来吧!


宣告 UserManager & RoleManager

UserManagerRoleManagerIdentity 用来处理会员和角色的实体
在这里我们会大量使用到他们来操作已经存入资料库的帐号们
所以必须先在 UserController.cs 中加入宣告:

private readonly RoleManager<IdentityRole> _roleManager;
private readonly UserManager<OnlineShopUser> _userManager;

public UserController(RoleManager<IdentityRole> roleManager, 
                      UserManager<OnlineShopUser> userManager)
{
    this._roleManager = roleManager;
    this._userManager = userManager;
}

角色列表

没什麽特别的,就是把他列出来而已

public IActionResult RoleList()
{
    var roles = _roleManager.Roles;
    return View(roles);
}

角色编辑

这边我想顺便把属於该角色的帐号列出来,就可以用到 GetUsersInRoleAsync 来取得内容

public async Task<IActionResult> RoleEdit(string id)
{
    if (id == null)
    {
        return NotFound();
    }
    var role = await _roleManager.FindByIdAsync(id);
    if (role == null)
    {
        return NotFound();
    }
    else
    {
        ViewBag.users = await _userManager.GetUsersInRoleAsync(role.Name);
    }
    return View(role);
}

public async Task<IActionResult> RoleEdit(IdentityRole role)
{
    if (role == null)
    {
        return NotFound();
    }
    else
    {
        var result = await _roleManager.UpdateAsync(role);
        if (result.Succeeded)
        {
            return RedirectToAction("ListUsers");
        }
        foreach (var error in result.Errors)
        {
            ModelState.AddModelError("", error.Description);
        }
     }
     return View();
}


<<:  [Day 20] 实作 - 介面篇4

>>:  Day 14 虚拟环境

Day15-Overloading

函式多载(overloading),今天顺着蚂蚁书的顺序先讨论函式多载(overloading)与样...

【Day 16】jQuery事件

jQuery事件 说明:是为响应 HTML 页面中的事件而订制的。 何谓事件(Events)? 网页...

【Day 27】C String - Practice 2

Q3 题目、输入输出格式 Sol 这题是要找B有没有在A字串中出现,我们就将 A 设为名叫first...

[Day 16] v-text和v-html

A new day!!今天要来讲的内容比较简单,篇幅甚至有点短ヽ(✿゚▽゚)ノ,但知识量可不会减少喔...

成为工具人应有的工具包-08 IECacheView

IECacheView OK 连续好几天发了断尾废文,今天我要再来发篇断尾废文,绝对没有自我放弃,之...