Menu Home

ASP.net MVC5 Easy Server Side Data Paging

You are building a MVC5 application, and suddenly the amount of data you show in your views are no long just ten or twenty items and you want to introduce paging, but how exactly do you do that? This post will tell you. It’s not rocket science, but I’m sure it’s a question that all Webforms developers like myself at some point will ask when they start build MVC applications.

I’m sure there are many ways to obtain paging, but I will just show one that I found easy. It uses the Nuget-package PagedList.Mvc, so the first step is to open the package manager console and type install-package "PagedList.Mvc" in your MVC5 application (if you used .net 4.5 when you created the project it should be MVC5).

Now you have the PageList.MVC package installed. Now lets see how simple it’s to add server side paging support to your list views controllers. Here is my very simple DataController that returns 100 lucky Guids. (This is obviously just for example purposes)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PagedList;
using WebApplication4.Models;

namespace WebApplication4.Controllers
{
    public class DataController : Controller
    {
        //
        // GET: /Data/
        public ActionResult Index(int? page)
        {
            int itemsPerPage = 25;
            int pageNumber = page ?? 1;
            List<Lucky> luckyGuids = new List<Lucky>();
            for (int i = 0; i < 100;i++ )
            {
                luckyGuids.Add(new Lucky() { Guid = Guid.NewGuid().ToString() });
            }
            return View(luckyGuids.ToPagedList(pageNumber, 25));
        }
    }
}

Worth noticing here is the using statement adding PagedList and how the ToPagedList extension method to IEnumerable/IQueryable collections takes a page number and a the number of items per page. Since the ToPagedList works on IQueryable, you can easily take advantage of it when working with database queries as well, very nice.

In the view the following has to be done, in order for the paging to work, otherwise it will just show the 25 first items.
Add the following code snippit where you want the pager to be typically after the table.

Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount

@Html.PagedListPager(Model, page => Url.Action("Index",new { page }))

For this code snipet to work, the model of the view must be changed from IEnumerable to PagedList.IPagedList as so

@model PagedList.IPagedList<WebApplication4.Models.Lucky>

If you try to run the application now, your view will not work, because the view engine doesn’t have a reference to the PagedList.Mvc namespace. The best way to solve that, is to update the web.config of the View folder with namespace reference to PagedList.Mvc my web.config’s system.web.webPages.razor section look like this:

<system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Optimization"/>
        <add namespace="System.Web.Routing" />
        <add namespace="WebApplication4" />
        <add namespace="PagedList.Mvc"/>
      </namespaces>
    </pages>
  </system.web.webPages.razor>

The last thing that needs to be changed, for the view to work properly is the use of @Html.DisplayNameFor extensions. Because the model collection is now changed to a IPagedList the DisplayNameFor syntax must be changed to

  @Html.DisplayNameFor(model => model.FirstOrDefault().Guid)

That’s all the steps there is to adding server side paging to a standard MVC list view. The final result looks like:
MVC5serversidepaging

Categories: Software

Tagged as:

Simon J.K. Pedersen

6 replies

  1. Thanks a lot.
    I found that somehow after install-package “PagedList.Mvc” Web.config file was not updated properly.
    So you explanation helped to solve this.

  2. Very nice tutorial.

    I’ve a below requirement:

    I have a view with one DropDownList and a Partial view.
    On selection of DropDown, result would be shown in Partial view, Which is happening properly.
    I need to implement Pagination in my Partial view html table result.
    [Result is coming from SQL Stored proc based on Current Page Index and PageSize].
    Based on Total row count from stored proc, I need to display pagination.
    How to achieve this ? (Most of the examples are based on Client side pagination)

    Kindly help me.

  3. It’s just some sample data so I have something to show in the table. Obviously you probably have some more interesting data, that needs paging 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *