ahp
ahp

Reputation: 397

How to retrieve all users in role using GetUsersInRoleAsync Method and display it the view as per below implementation in .net Core MVC

This post going to be a bit long so kindly please bear with me. Please do not hesitate to ask for clarifications if required. I will post my current implementation below which works perfectly but I found the built-in function GetUsersInRoleAsync. I would like to know how I can modify my below controller, model, and view to

  1. Get User roles using GetUsersInRoleAsync Method
  2. Then retrieve those details in my view

Current Code Implementation.

Model

using System.ComponentModel.DataAnnotations;

namespace MyApp.Models.ViewModels
{
    public class RoleViewModel
    {
        public RoleViewModel()
        {
            Users = new List<string>();
        }
        public string? Id { get; set; }

        [Required]
        [Display(Name = "Role Name")]
        public string Name { get; set; } = default!;

        public List<string>? Users { get; set; }

    }
}

Controller

[HttpGet]
public async Task<IActionResult> Read(string? id)
{
    var role = await roleManager.FindByIdAsync(id);
    if (role == null)
    {
        TempData[Helper.ErrorMessage] = "Role not found";
        return View("NotFound");
    }
    var model = new RoleViewModel
    {
        Id = role.Id,
        Name = role.Name
    };
    foreach (var user in userManager.Users)
    {
        if (await userManager.IsInRoleAsync(user, role.Name))
        {
            model.Users?.Add(user.UserName);
        }
    }
    return View(model);
}

View

@model MyApp.Models.RoleViewModel

<form method="get" asp-action="Read">
    <div class="row g-3">
        <div class="form-group col-sm-6">
            <label asp-for="Name" class="form-label"></label>
            <input asp-for="Name" class="form-control" type="text" disabled readonly>
        </div>
    </div>
    <div class="card mt-5">
        <div class="card-header">
            <ul class="nav nav-tabs card-header-tabs">
                <li class="nav-item">
                    <a class="nav-link active" aria-current="true">Users</a>
                </li>
            </ul>
        </div>
        <div class="card-body">
            <h5 class="card-title">Users</h5>
            <p class="card-text">List of users in this Role</p>
            <div class = "my-3">
            @if (Model?.Users?.Count>0)
            {
                foreach (var user in Model.Users)
                {
                    <li class="card-title">@user</li>
                }
            }
            else
            {
                <partial name="_NoData" />
            }
            </div>
        </div>
    </div>
    <partial name="_FooterMenuRead" />
</form>

Upvotes: 2

Views: 1792

Answers (2)

ahp
ahp

Reputation: 397

The best way I found to do it without any loops is to modify the controller as follows:

[HttpGet]
public async Task<IActionResult> Read(string? id)
{
    var role = await roleManager.FindByIdAsync(id);
    if (role == null)
    {
        TempData[Helper.ErrorMessage] = "Role not found";
        return View("NotFound");
    }
    var userList = await userManager.GetUsersInRoleAsync(role.Name);
    RoleViewModel? model = new()
    {
        Id = role.Id,
        Name = role.Name,
        Users = userList
    };
    return View(model);
}

Code in View remains same as in question

Upvotes: 0

Xinran Shen
Xinran Shen

Reputation: 9993

you can change your controller like this:

            [HttpGet]
            public async Task<IActionResult> Read(string? id)
            {
               
                var role = await roleManager.FindByIdAsync(id);
                if (role == null)
                {
                    TempData[Helper.ErrorMessage] = "Role not found";
                    return View("NotFound");
                }
                var model = new RoleViewModel
                {
                    Id = role.Id,
                    Name = role.Name
                };
                
                foreach (var user in await userManager.GetUsersInRoleAsync(role.Name))
                {
                    model.Users?.Add(user.UserName);
                }
                return View(model);
            }

Upvotes: 1

Related Questions