blazorblazor-server-sideuser-management

How can I list all users in a CRUD in Blazor?


I'm trying to get a CRUD page for usermanagement in a Blazor Server environment. I tried the following code:

The controller:

    [HttpGet]
    public async Task<ActionResult<IEnumerable<ApplicationUser>>> getUsers()
    {
        return _context.Users.ToList();
    }

The Razor Page:

@page "/administration/"
@inject HttpClient httpClient

@code {
    protected override async Task OnInitializedAsync()
    {
        var users = await httpClient.GetFromJsonAsync<List<ApplicationUser>> 
        ("api/AdministrationController");
    }
}

The problem is that ApplicationUser is not recognized within the Razor view. I tried injecting Microsoft.AspNetCore.Identity but this is also not available within the Razor View on client side.

How do I get all the users in a razor view with use of a controller?


Solution

  • You could introduce a DTO object for your API and use that from the Blazor application.

     [HttpGet]
        public async Task<ActionResult<IEnumerable<ApplicationUserDto>>> getUsers()
        {
            var users =  _context.Users.ToList();
            // convert ApplicationUser --> ApplicationUserDto here
            // AutoMapper/Mapster are good for this
            
        }
    

    Then, in your Razor page, you can work with the DTOs:

    @code {
        protected override async Task OnInitializedAsync()
        {
            var userDtos = await httpClient.GetFromJsonAsync<List<ApplicationUserDto>> 
            ("api/AdministrationController");
        }
    }
    

    The DTO is a simple POCO with all the ApplicationUser fields you want, ie:

    public class ApplicationUserDto
    {
      public Guid Id { get; init; }
      public string Username { get; init; }
      ... etc ...
    }