Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Creating roles in asp.net core

Suggested Videos
Part 75 - ASP.NET core remote validation | Text | Slides
Part 76 - Custom validation attribute in asp.net core | Text | Slides
Part 77 - Extend IdentityUser in ASP.NET Core | Text | Slides

In this video we will discuss creating roles in asp.net core using the ASP.NET Core Identity API.

RoleManager in ASP.NET Core

  • To create a user in asp.net core we use UserManager class. Similarly, to create a role, we use RoleManager class provided by asp.net core
  • The built-in IdentityRole class represents a Role
  • RoleManager class performs all the CRUD operations i.e Creating, Reading, Updating and Deleting roles from the underlying database table AspNetRoles
  • To tell the RoleManager class to work with IdentityRole class, we specify IdentityRole class as the generic argument to RoleManager 
  • RoleManager is made available to any controller or view by asp.net core dependency injection system

public class AdministrationController : Controller
{
    private readonly RoleManager<IdentityRole> roleManager;

    public AdministrationController(RoleManager<IdentityRole> roleManager)
    {
        this.roleManager = roleManager;
    }
}

Controller code to create a new role

The code is commented where necessary and is self-explanatory. You get a validation error, if you try to create a role with the same name that already exists.

using EmployeeManagement.ViewModels;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

namespace EmployeeManagement.Controllers
{
    public class AdministrationController : Controller
    {
        private readonly RoleManager<IdentityRole> roleManager;

        public AdministrationController(RoleManager<IdentityRole> roleManager)
        {
            this.roleManager = roleManager;
        }

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

        [HttpPost]
        public async Task<IActionResult> CreateRole(CreateRoleViewModel model)
        {
            if (ModelState.IsValid)
            {
                // We just need to specify a unique role name to create a new role
                IdentityRole identityRole = new IdentityRole
                {
                    Name = model.RoleName
                };

                // Saves the role in the underlying AspNetRoles table
                IdentityResult result = await roleManager.CreateAsync(identityRole);

                if (result.Succeeded)
                {
                    return RedirectToAction("index", "home");
                }

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

            return View(model);
        }
    }
}

Create Role View Model

In ASP.NET core to create a role, all we need is a unique name for the role. We decorated the RoleName property with the [Required] attribute as it is a required field.

using System.ComponentModel.DataAnnotations;

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

Create Role View

@model CreateRoleViewModel

@{
    ViewBag.Title = "Create New Role";
}

<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">
                Create Role
            </button>
        </div>
    </div>
</form>

asp.net core tutorial for beginners

No comments:

Post a Comment

It would be great if you can help share these free resources