The main objective of the article is:
- Implements Pagination.
Implement Pagination In API Project:
Let's change our HTTP GET Endpoint where we have to fetch the total number of records in the API response.
Let's create a new API response like 'SuperHeroesContainerDto'.
API_Project/Dtos/SuperHeroesContainerDto.cs:
namespace Dot7.Api.Dtos { public class SuperHeroesContainerDto { public int TotalCount { get; set; } public List<SuperHeroesDto> SuperHeroes { get; set; } } public class SuperHeroesDto { public int Id { get; set; } public string? Name { get; set; } public string? Franchise { get; set; } public string? Gender { get; set; } public string? ImageURL { get; set; } } }
- Here we have properties like 'TotalCount' and a collection of 'SuperHeroesDto'.
Now create an auto mapper profiler class like 'AppMapperProfile.cs' in the 'Common' folder(new folder).
API_Project/Common/AppMapperProfile.cs:
using AutoMapper; using Dot7.Api.Data.Entities; using Dot7.Api.Dtos; namespace Dot7.Api.Common { public class AppMapperProfile: Profile { public AppMapperProfile() { CreateMap<SuperHeroes, SuperHeroesDto>(); } } }
- Created mapper configuration between 'SuperHeroes' & 'SuperHeroesDto'.
API_Project/Program.cs:
builder.Services.AddAutoMapper(typeof(Program));Let's update the return type of 'GetSuperHeroesAsync' method definition in 'ISuperHeroesService'.
API_Project/Services/ISuperHeroesService.cs:
Task<SuperHeroesContainerDto> GetSuperHeroesAsync(SuperHeroFiltersDto filters);Let's update the logic in the 'GetSuperHeroesAsync' method.
API_Project/Services/SuperHeroesService.cs:
public async Task<SuperHeroesContainerDto> GetSuperHeroesAsync(SuperHeroFiltersDto filters) { var superHereos = _myWorldDbContext.SuperHeroes.AsQueryable(); if(!string.IsNullOrEmpty(filters.Sort) && !string.IsNullOrEmpty(filters.OrderBy)) { if(filters.Sort.ToLower() == "id" && filters.OrderBy.ToLower() == "asc") { superHereos = superHereos.OrderBy(_ => _.Id); } else if (filters.Sort.ToLower() == "id" && filters.OrderBy.ToLower() == "desc") { superHereos = superHereos.OrderByDescending(_ => _.Id); } else if (filters.Sort.ToLower() == "franchise" && filters.OrderBy.ToLower() == "asc") { superHereos = superHereos.OrderBy(_ => _.Franchise); } else if (filters.Sort.ToLower() == "franchise" && filters.OrderBy.ToLower() == "desc") { superHereos = superHereos.OrderByDescending(_ => _.Franchise); } } if (!string.IsNullOrEmpty(filters.Search)) { superHereos = superHereos.Where(_ => _.Franchise.ToLower() == filters.Search.ToLower()); } int totalCount = await superHereos.CountAsync(); int skip = ((filters.PageNumber - 1) * filters.PageSize); int take = filters.PageSize; superHereos = superHereos.Skip(skip).Take(take); var dbSuperHeroes = await superHereos.ToListAsync(); var resultSuperHereos = _mapper.Map<List<SuperHeroesDto>>(dbSuperHeroes); return new SuperHeroesContainerDto { TotalCount = totalCount, SuperHeroes = resultSuperHereos }; }
- (Line: 30) Fetch the total number of records from the database.
- (Line: 32-35) Here 'Skip' means the total number of records that needs to be skipped. Here 'take' means total records to fetch
- (Lines: 36&37) Here mapping the 'SuperHeroes' to 'SuperHeroesDto'.
Implement Pagination In Blazor WebAssembly Application:
Let's implement the MudBlazor pagination in 'AllSuperHeroes.razor'.
BlazorWasm_Project/Pages/SuperHeroes/AllSuperHeroes.razor:(HTML Part)
<div class="d-flex ma-2"> <MudGrid> <MudItem md="4"> <MudSelect Margin="Margin.Dense" Class="mt-2" T="string" Label="Sorting" Variant="Variant.Text" ValueChanged="DoSorting"> <MudSelectItem Value="@("id-by-desc")">ID BY Desc</MudSelectItem> <MudSelectItem Value="@("id-by-asc")">ID By Asc</MudSelectItem> <MudSelectItem Value="@("franchise-by-desc")">Franchise BY Desc</MudSelectItem> <MudSelectItem Value="@("franchise-by-asc")">Franchise By Asc</MudSelectItem> </MudSelect> </MudItem> <MudItem md="4"> <MudTextField @bind-Value="SearchKey" Label="Search" Variant="Variant.Text" Adornment="Adornment.End" AdornmentIcon="@Icons.Material.Filled.Search" OnAdornmentClick="DoSearch" AdornmentColor="Color.Primary" /> </MudItem> <MudItem md="4"> <MudPagination Color="Color.Primary" Count="@GetTotalPages()" SelectedChanged="HandlePaging" /> </MudItem> </MudGrid> </div>
- (Line: 14-16) Configured the 'MudPagination' component. The 'Count' property is registered with 'GetTotalPages'. The 'Count' property is used to display the page numbers. The 'SelectedChanged' event raises on clicking page controls.
@code { private List<SuperHeroesVM> allHeroes = new List<SuperHeroesVM>(); private string SortingKey { get; set; } private string SearchKey{ get; set; } private int TotalCount{ get; set; } private int PageNumber { get; set; } private int PageSize{ get; set; } protected override async Task OnInitializedAsync() { PageNumber = 1; PageSize = 5; await GetAllSuperHeroesAsync(); } private async Task GetAllSuperHeroesAsync() { var url = "/api/superheroes"; var sortingParams = GetSoringValues(); url = $"{url}?sort={sortingParams.Sort ?? string.Empty}&orderby={sortingParams.OrderBy ?? string.Empty}&search={SearchKey ?? string.Empty}&PageSize={PageSize}&PageNumber={PageNumber}"; var result = await Http.GetFromJsonAsync<SuperHeroesContainerVM>(url); allHeroes = result.SuperHeroes; TotalCount = result.TotalCount; } private (string Sort, string OrderBy) GetSoringValues() { if (!string.IsNullOrEmpty(SortingKey)) { if (SortingKey.ToLower() == "id-by-desc") { return ("id", "desc"); } else if (SortingKey.ToLower() == "id-by-asc") { return ("id", "asc"); } else if (SortingKey.ToLower() == "franchise-by-desc") { return ("franchise", "asc"); } else if (SortingKey.ToLower() == "franchise-by-desc") { return ("franchise", "asc"); } } return (string.Empty, string.Empty); } private async Task DoSorting(string sortKey) { PageNumber = 1; SortingKey = sortKey; await GetAllSuperHeroesAsync(); } private async Task DoSearch() { PageNumber = 1; await GetAllSuperHeroesAsync(); } protected int GetTotalPages() { var totalpages = ((double)TotalCount / (double)PageSize); return Convert.ToInt32(Math.Ceiling(totalpages)); } private async Task DeleteSuperHeroesAsync(int id) { var parameters = new DialogParameters(); parameters.Add("Id", id); var dialog = await _dialogService.ShowAsync<SuperHeroesDeletePopup>("Delete Confirmation", parameters, new DialogOptions { }); var result = await dialog.Result; if (!result.Canceled) { allHeroes = allHeroes.Where(_ => _.Id != id).ToList(); TotalCount = TotalCount - 1; StateHasChanged(); } } private async Task HandlePaging(int page) { PageNumber = page; await GetAllSuperHeroesAsync(); } }
- (Line: 5) The 'TotalCount' property to save the total number of records from the API.
- (Line: 6) The 'PageNumber' property represents the current page.
- (Line: 7) The 'PageSize' property represents number of items to display on the page
- (Line: 55&62) Here we reset the 'PageNumber' to '1' while sorting and searching.
- (Line: 66-70) The 'GetTotalPages' results a total number of page numbers to display
- (Line: 88-90) The 'hadlePaging()' method gets invoked for every page control-click.
Support Me!
Buy Me A Coffee
PayPal Me
Wrapping Up:
Hopefully, I think this article delivered some useful information on the.NET7 Blazor WebAssembly CRUD sample. using I love to have your feedback, suggestions, and better techniques in the comment section below.
Refer:
Part-2 | Blazor WebAssembly | .Net7 API | MudBlazor | CRUD - Create API Project
Part-3 | Blazor WebAssembly | .Net7 API | MudBlazor | CRUD - Implement Read Operation
Part-3 | Blazor WebAssembly | .Net7 API | MudBlazor | CRUD - Implement Read Operation
Part-4 | Blazor WebAssembly | .Net7 API | MudBlazor | CRUD - Implement Create Operation
Part-5 | Blazor WebAssembly | .Net7 API | MudBlazor | CRUD - Implement Update Operation
Part-6 | Blazor WebAssembly | .Net7 API | MudBlazor | CRUD - Implement Delete Operation
Part-7 | Blazor WebAssembly | .Net7 API | MudBlazor | CRUD - Sorting
Part-8 | Blazor WebAssembly | .Net7 API | MudBlazor | CRUD - Implement Search
Part-5 | Blazor WebAssembly | .Net7 API | MudBlazor | CRUD - Implement Update Operation
Part-6 | Blazor WebAssembly | .Net7 API | MudBlazor | CRUD - Implement Delete Operation
Part-7 | Blazor WebAssembly | .Net7 API | MudBlazor | CRUD - Sorting
Part-8 | Blazor WebAssembly | .Net7 API | MudBlazor | CRUD - Implement Search
Comments
Post a Comment