Skip to content

Instantly share code, notes, and snippets.

@HammadMaqbool
Created April 24, 2022 16:45
Show Gist options
  • Save HammadMaqbool/7eaa8467cc089b35812d6c713fd40cb6 to your computer and use it in GitHub Desktop.
Save HammadMaqbool/7eaa8467cc089b35812d6c713fd40cb6 to your computer and use it in GitHub Desktop.
This is the complete code of how to implement the pagination in the AspNetCore MVC (.NET6) all portions are defined.

Make a class PaginatedList in Model folder 📂

public class PaginatedList<T> : List<T>
    {
        public int PageIndex { get; private set; }
        public int TotalPages { get; private set; }

        public PaginatedList(List<T> items, int count, int pageIndex, int pageSize)
        {
            PageIndex = pageIndex;
            TotalPages = (int)Math.Ceiling(count / (double)pageSize);

            this.AddRange(items);
        }

        public bool HasPreviousPage => PageIndex > 1;

        public bool HasNextPage => PageIndex < TotalPages;

        public static async Task<PaginatedList<T>> CreateAsync(IQueryable<T> source, int pageIndex, int pageSize)
        {
            var count = await source.CountAsync();
            var items = await source.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync();
            return new PaginatedList<T>(items, count, pageIndex, pageSize);
        }
    }

Now in Controller Modify the Home Action Like this

public async Task<IActionResult> Index(int pagenumber=1)
     {
         return View(await PaginatedList<Post>.CreateAsync(context.Db_Table,pagenumber,2));
     }

Lets move towards View and add this code on top of the View

@using YourNameSpace.Models
@model PaginatedList<Model>

This is How I designed the Next and Previous buttons in the footer of the page

<!-- Footer -->
 @{
     var prevDisabled = !Model.HasPreviousPage ? "disabled" : "";
     var nextDisabled = !Model.HasNextPage ? "disabled" : "";
 }
<footer class="w3-container w3-dark-grey w3-padding-32 w3-margin-top">
<a class="w3-button w3-black w3-padding-large w3-margin-bottom w3-@prevDisabled" asp-action="Index" asp-route-pagenumber="@(Model.PageIndex-1)">Previous</a>
<a class="w3-button w3-black w3-padding-large w3-margin-bottom w3-@nextDisabled" asp-action="Index" asp-route-pagenumber="@(Model.PageIndex+1)" >Next »</a>

</footer>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment