Paging in ASP.NET Core MVC

Problem Defination :- When we fetch thousands of records from database and show these records in MVC grid then we are not able to show all the records into the Grid due to visibility of records and performance we represent limited records and we need to implement a paging with page numbers to easily navigate on the records so here we have implemented paging logic.

Image is not available

Image is not available

Implementation :- To implement paging functionality firstly we have to follow below steps

  • Create a Model Class for items.
  • Create a Controller named it Items.
  • Add these item model class into the DbContext class and then execute the migration commands.
  • Create a Action Method for List the items and named it as Index.
  • Create a View for Index method.
  • Create a Pager Class for paging logic.
  • Create a _Pager Partial View for paging design.

In The implemetation phase we will create one model class which is used for Items. Below is the code for Item Model class.

                
 public class Item
    {
        [Key]
        public int ItemId { get; set; }
        public string Name { get; set; }
        public string Brand { get; set; }
        public string Description { get; set; }
        public string Path { get; set; }
        [NotMapped]
        [Display(Name ="Choose Image")]
        public IFormFile ImagePath { get; set; }
    }
                            
                      

Below is the code for Pager class.

                
 public class Pager
    {
        public int TotalItems { get; set; }
        public int PageSize { get; set; }
        public int CurrentPage { get; set; }
        public int TotalPages { get; set; }
        public int StartPage { get; set; }
        public int EndPage { get; set; }
        public Pager()
        {

        }
        public Pager(int totalItems,int page,int pageSize=5)
        {
            int totalPages=(int)Math.Ceiling((decimal)totalItems/(decimal)pageSize);
            int currentPage = page;
            int startPage = currentPage - 5;
            int endPage = currentPage + 4;
            if(startPage<=0)
            {
                endPage=endPage-(startPage-1);
                startPage = 1;
            }
            if(endPage>totalPages)
            {
                endPage = totalPages;
                if(endPage>10)
                {
                    startPage = endPage - 9;
                }
            }
            TotalItems = totalItems;
            CurrentPage = currentPage;
            PageSize = pageSize;
            TotalPages = totalPages;
            StartPage = startPage;
            EndPage = endPage;
        }
    }
                            
                        

Now create a DBContext class and named it as demoDBcontext and add the below one DBSet into this class that will generate the table into the database when you run the migration commands.

                
public DbSet Items { get; set; }
                        
                        

Now Create the Controller with named Items and write the below Action Methods into it. Index() is the method in which we are fetching the list of records from database and show into the view.

                
 public class ItemsController : Controller
    {
        private readonly AmazonShoppingDBContext _db;
        private readonly IWebHostEnvironment webHostEnvironment;
        public ItemsController(AmazonShoppingDBContext db,IWebHostEnvironment environment)
        {
            _db = db;
            webHostEnvironment = environment;

        }

        public IActionResult Index(int pg=1)
        {
            var data = _db.Items.ToList();
            const int pageSize = 5;
            if (pg < 1)
                pg = 1;
            int recsCount = data.Count;

           var pager=new Pager(recsCount,pg,pageSize);
            int recSkip = (pg - 1) * pageSize;
            var dataList=data.Skip(recSkip).Take(pager.PageSize).ToList();  
            ViewBag.Pager=pager;
            return View(dataList);
        }
}
                            
                        

List of Items to present into grid :- We have implemented a action method Index which is retrieving the items record from database table into the list and return to view,below is the code for controller action method.

                    
        public IActionResult Index(int pg=1)
        {
            var data = _db.Items.ToList();
            const int pageSize = 5;
            if (pg < 1)
                pg = 1;
            int recsCount = data.Count;

           var pager=new Pager(recsCount,pg,pageSize);
            int recSkip = (pg - 1) * pageSize;
            var dataList=data.Skip(recSkip).Take(pager.PageSize).ToList();  
            ViewBag.Pager=pager;
            return View(dataList);
        }
}
                            
                        

Pager Partial View :- This view is used for design a pagination bar and next,previous and first and last button in pagination bar.

Image is not available

Index View :- Design the Index view for presenting the item list into the grid and use the pager partial view for pagination bar like below image

Image is not available

So we have implemented the paging logic successfully and you can test the same in your local system.

Image is not available

About the Author
Sudheer Singh Chouhan is a Software Engineer having Expertise in Development Design and Architecting the applications , Project Management , Designing Large Scale Databases in SQL Server since last 17 Years.
Skill Sets :- Microsoft .NET technologies like ASP.Net Core, Web API, LINQ, Web Forms, WinForms, SQL Server, EntityFramework, Design Patterns, Solid Principles, Microservices, AWS Cloud.