Server side pagination in ASP.NET controler that supports any entity
For one of the Angular JS applications I am working on needed pagination on server side (ASP.NET Core). So thought about creating it, so it supports any entity as it a very common scenario on server side.
Create a class PaginatedResult.cs below is the code for it.
public class PaginatedResult<T> { public Pagination Pagination; public IEnumerable<T> Result { get; set; } private const int DefaultPage = 1; private const int DefaultPageSize = 10; public PaginatedResult(IQueryable<EntityBase> entities, int totalItems, int? page, int? pageSize) { var currentPageSize = pageSize ?? DefaultPageSize; var currentPage = page ?? DefaultPage; var totalPages = (int)Math.Ceiling((double)totalItems / currentPageSize); var pagedEntities = entities.Skip((currentPage - 1) * currentPageSize).Take(currentPageSize).ToList(); Result = Mapper.Map<IEnumerable<T>>(pagedEntities); // FYI - AutoMapper Pagination = new Pagination { CurrentPage = currentPage, TotalItems = totalItems, TotalPages = totalPages, ItemsPerPage = currentPageSize }; } }
Below is the controller code that utilising the pagination.
[HttpGet("")] public IActionResult Get(string searchTerm, int? page = null, int? pageSize = null) { // Logic to get the count and items from database var totalItems = // get the count; var entities = // get the items from ; return Ok(new PaginatedResult<QuestionViewModel>(entities, totalItems, page, pageSize)); }
That is all, let me know what you think about it.