Paging with LINQ in ASP.NET MVC

Apr 25, 2009   //   by Michael D. Irizarry   //   JavaScript  //  No Comments

Here’s a really neat and simple way to add pagination to your LINQ results in ASP.NET MVC. The simple class can be also implemented in non ASP.NET MVC projects.
Note: You can change the source parameter to be List or just add a method overload.

PaginatedList Class

using System;
using System.Linq;
using System.Collections.Generic;

namespace MyApp.Helpers
{
    public class PaginatedList : List
    {

        public int PageIndex { get; private set; }
        public int PageSize { get; private set; }
        public int TotalCount { get; private set; }
        public int TotalPages { get; private set; }

        public PaginatedList(IQueryable source, int pageIndex, int pageSize)
        {
            PageIndex = pageIndex;
            PageSize = pageSize;
            TotalCount = source.Count();

            TotalPages = (int) Math.Ceiling(TotalCount / (double)PageSize);

            this.AddRange(source.Skip((PageIndex) * PageSize).Take(PageSize));
        }

        public bool HasPreviousPage
        {
            get {return (PageIndex > 0);}
        }

        public bool HasNextPage {
            get {return (PageIndex+1 < TotalPages);}
        }

    }
}

Controller

        public ActionResult Index(int? page)
        {
            int pageSize = 15;
            var content = MyAppRepository.FindContentByDate().ToList();
            var pagedContent = new PaginatedList(content, page ?? 0, pageSize);

            return View("Index", pagedContent);
        }

View


Routes in Global.asax

routes.MapRoute(
                "Index",
                "Index/Page/{page}",
                new { controller = "Home", action = "Index", page = 0 }
            );

Leave a comment