How to Add Pagination in Dotnet WebApi
Are you facing trouble in adding pagination in .Net WebApi? If so then you are at the right place. In this blog, I have shared every step with a source code to add pagination in dotnet webapi.
To add pagination in a .NET Web API using a generic pagination class, you can use the following steps:
1. Create a PagingParameterModel class to hold the paging information such as page number and page size:
public class PagingParameterModel
{
public int PageNumber { get; set; } = 1;
public int PageSize { get; set; } = 10;
}
2. Create a Generic Pagination class that holds the pagination information and the data that is to be returned.
public class PagedData<T> where T : class
{
public List<T> Data { get; set; }
public int PageNumber { get; set; }
public int PageSize { get; set; }
public int TotalRecords { get; set; }
public int TotalPages { get; set; }
}
3. In your API controller, add the PagingParameterModel as a parameter in the action method and use it to retrieve the appropriate page of data from the repository and then create an instance of the generic pagination class and return it.
[HttpGet]
public IActionResult Get(PagingParameterModel paging)
{
var data = _repository.Get(paging.PageNumber, paging.PageSize);
var totalRecords = _repository.GetTotalRecords();
var totalPages = (int)Math.Ceiling((double)totalRecords / paging.PageSize);
var pagedData = new PagedData<T>
{
Data = data,
PageNumber = paging.PageNumber,
PageSize = paging.PageSize,
TotalRecords = totalRecords,
TotalPages = totalPages
};
return Ok(pagedData);
}
4. On the client side you can use this information to create a pagination UI.
Note: you may need to adjust this code based on your specific requirements and the structure of your application.