Welcome to our blog Contact Us Subscribe!

How to Add Pagination in Dotnet WebApi

In this blog I have shared every steps with a source code to add pagination in dotnet webapi. This will easily helps to add pagination on webapi.
Anonymous

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.
How 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.

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.