Updated 2012-04-23: Version 2.0: https://blogs.taiga.nl/martijn/2012/04/23/mvcpaging-2-0/
Updated 2011-05-12: Added NuGet package: https://blogs.taiga.nl/martijn/2011/05/12/nuget-package-for-mvc-pager/
Updated 2011-03-22: Changed download link: https://github.com/martijnboland/MvcPaging. See also https://blogs.taiga.nl/martijn/2011/03/23/mvc-pager-update-now-with-ajax-support/
Updated 2009-02-04: Upgraded source and demo to ASP.NET MVC RC1
Updated 2009-01-16: Upgraded source and demo to ASP.NET MVC Beta
Updated 2008-09-09: Source and Demo now use ASP.NET MVC preview 5
On my latest gig, we used ASP.NET MVC and it was a very pleasant experience! Very clean code, clean html output and the productivity was great (which is not very common when using a technology for the first time).
Of course, since ASP.NET MVC isn’t finished yet, it leaves something to desire. At one time we needed paging and there isn’t an out-of-the-box solution for it (yet). Some googling revealed that others had already addressed this, but to be honest, I wasn’t entirely pleased with the solutions, so I grabbed the best parts and build a generic solution out of it.
I’m in a hurry, take me to the download immediately
IPagedList
First, there was the PagedList
Html.Pager()
After choosing the IPagedList
We’re assuming that the page links point to the the current controller and current action. Alternatively, it’s possible to supply a different action:
Combining the Pager html helper and IPagedList
results in this:
You probably recognize the digg-style appearance of the pager. Thanks to the ASP.NET MVC sample application KIGG for inspiration :).
Internally, the pager uses RouteTable.Routes.GetVirtualPath() to render the url’s so the page url’s can be configured via routing to create nice looking url’s like for example ‘/Categories/Shoes/Page/1’ instead of ‘/Paging/ViewByCategory?name=Shoes&page=1’.
Advanced scenarios
Many scenarios where you want to use paging also use filtering. It’s possible to pass extra parameters to the Pager helper via a RouteValueDictionary or an anonymous type. This adds these parameters to the page links that are generated:
That’s it. A complete solution with demo project can be downloaded below. Feel free to leave any comments or remarks. One of the things I’m not happy about is that I failed to properly unit test the pager, but that’s for a different post.
Download
Download the paging sample solution, incl. the demo MVC web project
Check also the AJAX version of the pager written by Daniel Iglesias: http://danieliglesiaseng.blogspot.com/2010/01/ajax-paging-with-aspnet-mvc.html.