Saturday, September 7, 2019

Get list of roles in asp.net core

we will discuss how to retrieve and display all roles in asp.net core using the Identity API.

We want to display 
  • Role ID
  • Role Name and 
  • A pair of buttons to Edit and Delete a role

get all roles in asp.net identity



Roles property of RoleManager class
  • Roles property of RoleManager class returns the list of all IdentityRole objects
  • Pass the list of IdentityRole objects to the view for display
[HttpGet]
public IActionResult ListRoles()
{
    var roles = roleManager.Roles;
    return View(roles);
}

Here is the complete controller code

using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;

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

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

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

        // Rest of the code
    }
}

List Roles View 
  • ID property of the IdentityRole object returns the role ID
  • Name property of the IdentityRole object returns the role Name
  • We are using Bootstrap 4 cards for styling the list of roles
@model IEnumerable<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>

    foreach (var role in Model)
    {
        <div class="card mb-3">
            <div class="card-header">
                Role Id : @role.Id
            </div>
            <div class="card-body">
                <h5 class="card-title">@role.Name</h5>
            </div>
            <div class="card-footer">
                <a href="#" class="btn btn-primary">Edit</a>
                <a href="#" class="btn btn-danger">Delete</a>
            </div>
        </div>
    }
}
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>
}


No comments:

Post a Comment

How to register multiple implementations of the same interface in Asp.Net Core?

 Problem: I have services that are derived from the same interface. public interface IService { } public class ServiceA : IService { ...