码迷,mamicode.com
首页 > Web开发 > 详细

Asp.Net Core中的角色

时间:2019-09-21 12:26:28      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:取消   hold   mit   inpu   按钮   addm   null   syn   new   

  在前面介绍中我们知道了Asp.Net Core Identity中创建用户使用到的类UserManager<IdentityUser>,同样的,创建角色我们需要使用RoleManager<IdentityRole>。

  接下来我们就来看看如何创建角色。

  先定义ViewModel

namespace StudentManagement.ViewModels
{
    public class CreateRoleViewModel
    {
        [Required]
        [Display(Name = "角色")]
        public string RoleName { get; set; }
    }
}

  创建AdminController

namespace StudentManagement.Controllers
{
    public class AdminController : Controller
    {
       private readonly RoleManager<IdentityRole> roleManager;
    private readonly UserManager<ApplicationUser> userManager;
public AdminController(RoleManager<IdentityRole> roleManager, UserManager<ApplicationUser> userManager) { this.roleManager = roleManager;
       this.userManager = userManager;
} [HttpGet] public IActionResult CreateRole() { return View(); } [HttpPost] public async Task<IActionResult> CreateRole(CreateRoleViewModel model) { if (ModelState.IsValid) { //我们只需要指定一个不重复的角色名称来创建新角色 IdentityRole identityRole = new IdentityRole { Name = model.RoleName }; //将角色保存在AspNetRoles表中 IdentityResult result = await roleManager.CreateAsync(identityRole); if (result.Succeeded) { return RedirectToAction("ListRoles", "Admin"); } foreach (IdentityError error in result.Errors) { ModelState.AddModelError("", error.Description); } } return View(model); } }

  创建视图

@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="Name">
            <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>

  创建完角色,我们需要显示它,在AdminController中添加下面的ListRoles方法

[HttpGet]
public IActionResult ListRoles()
{
    var roles = roleManager.Roles;
    return View(roles);
}

  新建ListRoles视图,既然有列表,那么就应该存在编辑和删除角色的功能

@model IEnumerable<IdentityRole>

@{
    ViewBag.Title = "角色列表";
}

<h1>所有角色列表</h1>

@if (Model.Any())
{
    <a class="btn btn-primary mb-3" style="width:auto" asp-action="CreateRole"
       asp-controller="admin">添加新角色</a>

    foreach (var role in Model)
    {
        <div class="card mb-3">
            <div class="card-header">
                角色Id : @role.Id
            </div>
            <div class="card-body">
                <h5 class="card-title">@role.Name</h5>
            </div>
            <div class="card-footer">

                <form method="post" asp-action="DeleteUser" asp-route-id="@role.Id">
                    <a asp-controller="Admin" asp-action="EditRole"
                       asp-route-id="@role.Id" class="btn btn-primary">
                        编辑
                    </a>

                    <span id="confirmDeleteSpan_@role.Id" style="display:none">
                        <span>你确定你要删除?</span>
                        <button type="submit" class="btn btn-danger">是</button>
                        <a href="#" class="btn btn-primary"
                           onclick="confirmDelete(‘@role.Id‘, false)">否</a>
                    </span>

                    <span id="deleteSpan_@role.Id">
                        <a href="#" class="btn btn-danger"
                           onclick="confirmDelete(‘@role.Id‘, true)">删除</a>
                    </span>
                </form>


            </div>
        </div>
    }
}
else
{
    <div class="card">
        <div class="card-header">
            尚未创建任何角色
        </div>
        <div class="card-body">
            <h5 class="card-title">
                点击下面的按钮创建角色
            </h5>
            <a class="btn btn-primary" style="width:auto"
               asp-controller="admin" asp-action="CreateRole">
                创建角色
            </a>
        </div>
    </div>
}
[HttpPost]
public async Task<IActionResult> DeleteRole(string id)
{
    var role = await roleManager.FindByIdAsync(id);

    if (role == null)
    {
        ViewBag.ErrorMessage = $"无法找到ID为{id}的角色信息";
        return View("NotFound");
    }
    else
    {
        var result = await roleManager.DeleteAsync(role);

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

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

        return View("ListRoles");
    }
}
[HttpGet]
public async Task<IActionResult> EditRole(string id)
{
    //通过角色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
    };

    // 查询所有的用户
    foreach (var user in userManager.Users)
    {
        //如果用户拥有此角色,请将用户名添加到
        // EditRoleViewModel模型中的Users属性中
        //然后将对象传递给视图显示到客户端
        if (await userManager.IsInRoleAsync(user, role.Name))
        {
            model.Users.Add(user.UserName);
        }
    }

    return View(model);
}

//此操作方法用于响应HttpPost的请求并接收EditRoleViewModel模型数据
[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;

        //使用UpdateAsync更新角色
        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);
    }
}

   创建视图

@model EditRoleViewModel

@{
    ViewBag.Title = "编辑角色";
}

    <h1>编辑角色</h1>

<form method="post" class="mt-3">
    <div class="form-group row">
        <label asp-for="Id" class="col-sm-2 col-form-label"></label>
        <div class="col-sm-10">
            <input asp-for="Id" disabled class="form-control">
        </div>
    </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">
            <span asp-validation-for="RoleName" class="text-danger"></span>
        </div>
    </div>

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

    <div class="form-group row">
        <div class="col-sm-10">
            <button type="submit" class="btn btn-primary">更新</button>
            <a asp-action="ListRoles" class="btn btn-primary">取消</a>
        </div>
    </div>

    <div class="card">
        <div class="card-header">
            <h3>该角色中的用户</h3>
        </div>
        <div class="card-body">
            @if (Model.Users.Any())
            {
                foreach (var user in Model.Users)
                {
                    <h5 class="card-title">@user</h5>
                }
            }
            else
            {
                <h5 class="card-title">目前没有信息</h5>
            }
        </div>
        <div class="card-footer">
            <a asp-controller="Admin" asp-action="EditUsersInRole"
               asp-route-roleId="@Model.Id" class="btn btn-primary">
                添加或删除用户到角色中
            </a>
        </div>
    </div>
</form>

  有了角色之后,我们需要为角色添加用户,所以先创建 EditRoleViewModel 和 UserRoleViewModel。

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

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

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

    public List<string> Users { get; set; }
}
public class UserRoleViewModel
{
    public string UserId { get; set; }
    public string UserName { get; set; }
    public bool IsSelected { get; set; }
}
@model List<UserRoleViewModel>

@{
    var roleId = ViewBag.roleId;
}

<form method="post">
    <div class="card">
        <div class="card-header">
            <h2>在此角色中添加或删除用户</h2>
        </div>
        <div class="card-body">
            @for (int i = 0; i < Model.Count; i++)
            {
                <div class="form-check m-1">
                    <input type="hidden" asp-for="@Model[i].UserId" />
                    <input type="hidden" asp-for="@Model[i].UserName" />
                    <input asp-for="@Model[i].IsSelected" class="form-check-input" />
                    <label class="form-check-label" asp-for="@Model[i].IsSelected">
                        @Model[i].UserName
                    </label>
                </div>
            }
        </div>
        <div class="card-footer">
            <input type="submit" value="更新" class="btn btn-primary"
                   style="width:auto" />
            <a asp-action="EditRole" asp-route-id="@roleId"
               class="btn btn-primary" style="width:auto">取消</a>
        </div>
    </div>
</form>

  创建控制器的方法

[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);

        IdentityResult result = null;

        if (model[i].IsSelected && !(await userManager.IsInRoleAsync(user, role.Name)))
        {
            result = await userManager.AddToRoleAsync(user, role.Name);
        }
        else if (!model[i].IsSelected && await userManager.IsInRoleAsync(user, role.Name))
        {
            result = await userManager.RemoveFromRoleAsync(user, role.Name);
        }
        else
        {
            continue;
        }

        if (result.Succeeded)
        {
            if (i < (model.Count - 1))
                continue;
            else
                return RedirectToAction("EditRole", new { Id = roleId });
        }
    }

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

 

Asp.Net Core中的角色

标签:取消   hold   mit   inpu   按钮   addm   null   syn   new   

原文地址:https://www.cnblogs.com/jesen1315/p/11562213.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!