Created
October 4, 2023 07:09
-
-
Save HamidMolareza/c84172001b3e0ce16cd65a50873b88f2 to your computer and use it in GitHub Desktop.
Pagination for ASP MVC or Razor Pages
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class PaginationModel<T> : PageModel { | |
public int PageIndex { get; set; } | |
public int PageLimit { get; set; } | |
public int TotalItems { get; set; } | |
public List<T> Items { get; set; } = new(); | |
public bool IsValidPage { get; set; } | |
public async Task LoadItemsAsync(IQueryable<T> source, int? page, int? limit) { | |
if (page < 1 || limit < 1) { | |
IsValidPage = false; | |
return; | |
} | |
PageIndex = page ?? 1; | |
PageLimit = limit ?? 10; | |
TotalItems = await source.CountAsync(); | |
if (TotalItems == 0) { | |
IsValidPage = true; | |
return; | |
} | |
var totalPages = (int)Math.Ceiling(TotalItems / (double)PageLimit); | |
if (PageIndex > totalPages) { | |
IsValidPage = false; | |
return; | |
} | |
Items = await source | |
.Skip((PageIndex - 1) * PageLimit) | |
.Take(PageLimit).ToListAsync(); | |
IsValidPage = true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment