As promised in my last blog post about creating a reusable NHibernate paging extension method, here is some code that uses the IPagedList interface we created to render a nice looking pager control in an ASP.NET MVC site.
The Pager class contains the rendering logic for the pager control and makes use of the TagBuilder class supplied in the System.Web.Mvc namespace. Makes generating well-formatted HTML code a bit easier, in my opinion. The class itself is pretty boring, just pass in the IPagedList instance and BAM! There are some customization options as well like changing the text of the Next/Previous/First/Last links, showing or hiding the total record count, etc. One of the more interesting options is the EnableAjax property which, when set to true, renders the URL of each pager link as a hash link (/list#page=2) instead of a hard link (/list?page=2). This allows you to intercept the hash changed event using jQuery and dynamically update the page content using Ajax.
In typical MVC fashion, I created a couple extension methods that make calling the Pager class easy from a View. You can customize the settings however you like. Call any of these methods from your view and just pass in the IPagedList instance.
Here’s what the rendered pager markup looks like, pretty clean if I do say so myself.
It doesn’t take much to make this look nice with some CSS classes. Here’s a simple example.
And, finally, here’s what the pager looks like on the, err, page.