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<T> : List<T>
    {
 
        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<T> 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>(content, page ?? 0, pageSize);
 
            return View("Index", pagedContent);
        }

View

        <div id="nav_paging">
        <% if (Model.HasPreviousPage) { %>
        <div class="nav_prev">
            <%= Html.RouteLink("Previous", "Index", new { page = (Model.PageIndex - 1) })%>
        </div>
        <% } %>
 
        <% if (Model.HasNextPage) { %>
        <div class="nav_next">
            <%= Html.RouteLink("Next", "Index", new { page = (Model.PageIndex + 1) })%>
        </div>
        <% } %>
        </div>

Routes in Global.asax

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

Leave a comment