Thursday, November 21, 2019

Add & Display Roles in asp.net Core Identity | Asp.net Core Idnetity


Hello & As-salam u alikum ! , In the previous articles we had discussed about Client side validations,Remote Validations & Custom Validations, There is the reference in the below link.

https://dotnetcorecommunity.blogspot.com/2019/11/emailuser-name-already-taken-remote.html

At the moment, We are going to learn about roles in asp.net core identity, Before moving towards this topic I must suggest you to see these below articles for the basic or prior knowledge to understand about this concept.


1-Implementing Asp.net Core Identity |Authentication and Authorization| Introduction To Asp.net Core Identity | asp.net core 2.0 identity tutorial

2-Implementing Login Logout & Sign up Feature in Asp.net Core Identity using Sign in Manager | Login Log out show in Navigation Bar | Session Cookie Vs Persistence Cookie

3-Authorization In Asp.net Core Identity | AllowAnonymous & Authorize Attribute in Asp.net Core | Set Authorization Globally

Step# 1:  Add a new controller named as "AdministrationController" & add an action named as "ListRoles" to show the list of role present in the database.



using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AspCoreIdentity.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace AspCoreIdentity.Controllers
{
   [Authorize(Roles ="Admin")]
    public class AdministrationController : Controller
    {
        private readonly RoleManager<IdentityRole> roleManager;
        private readonly UserManager<ApplicationUser> userManager;
        private readonly ILogger<AdministrationController> logger;

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

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

}
Step# 2:  Add a view of ListRoles and paste the following HTML.


@model IEnumerable<Microsoft.AspNetCore.Identity.IdentityRole>

@{
    ViewBag.Title = "All Roles";
}

<h1>All Roles</h1>

@if (Model.Any())
{
    <a class="btn btn-primary mb-3" style="width:auto" asp-action="CreateRole"
       asp-controller="administration">Add new role</a>



    <table class="table table-dark">
        <thead>
            <tr>
                <th>ID</th>
                <th>Role Name</th>
                <th>Edit</th>
                <th>Delete</th>

            </tr>
        </thead>
        <tbody>



            @foreach (var role in Model)
            {

                <tr>
                    <td>@role.Id</td>
                    <td>@role.Name</td>
                    <td>
                        <a asp-action="EditRole" asp-controller="Administration"
                           asp-route-id="@role.Id" class="btn btn-primary">Edit</a>
                    </td>
                    <td>

                        <form method="post" asp-action="Deleterole" asp-route-id="@role.Id">


                            <span id="confirmDeleteSpan_@role.Id" style="display:none">
                                <span>Are you sure you want to delete?</span>
                                <button type="submit" class="btn btn-danger">Yes</button>
                                <a href="#" class="btn btn-primary"
                                   onclick="confirmDelete('@role.Id', false)">No</a>
                            </span>

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

                </tr>


            }

        </tbody>

    </table>


}
else
{
    <div class="card">
        <div class="card-header">
            No roles created yet
        </div>
        <div class="card-body">
            <h5 class="card-title">
                Use the button below to create a role
            </h5>
            <a class="btn btn-primary" style="width:auto"
               asp-controller="administration" asp-action="CreateRole">
                Create Role
            </a>
        </div>
    </div>
}

@section Scripts {
    <script src="~/js/CustomScript.js"></script>
}

Now Run the project & target the URL "https://localhost:44318/Administration/ListRoles"
you will not get any role because we didn't have created any role so the list would be empty for adding new Records we have to add a new action result Which we already had mentioned on view named as "CreateRole". This action will help us to add new role in the database.


  [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("ListRoles", "Administration");
                }

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

            return View(model);
        }

Add the above GET & POST methods in the Administrator Controller & add a view for this action method.



@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>

 When you run the project, you may be able to add new roles & can see the added roles on ListRole view.




Conclusion :
that's all for this blog, we have successfully
 Implement the Asp.net core Identity with Adding & displaying Role ,In the next coming articles we will discuss more details on this topic.Thank you for watching,Have a great day !


Subscribe to my Youtube  

0 Comments:

Post a Comment

Do not Add Spam links in the Comment Box

Subscribe to Post Comments [Atom]

<< Home