Simple pager for ASP.NET MVC

I needed simple pager for one of my ASP.NET MVC projects. I mean really simple pager – no new types my code should be aware of, no any other chemistry I don’t really need in early stages. As ASP.NET MVC has nothing to offer I wrote my own *really simple* pager implementation. Here is what I did.

NB! The code here is very fresh and I take it as a fast prototype solution. I provided it to you to give you simple pager you can use without knowing about too much details. You can quickly and easily use it in your ASP.NET MVC applications and application prototypes. Feel free to modify my code if you like.

To get pager built more optimally I created PagerBuilder class. It takes some parameters and based on them it generates pager mark-up when ToString() method is called (just like StringBuilder returns string with its contents when ToString() is called). This is my PagerBuilder.

public class PagerBuilder
{
   
private class PagerLink
    {
       
public string Title { get; set
; }
       
public int PageNo { get; set
; }
       
public string Class { get; set
; }
    }
 
   
private readonly string
_urlTemplate;
   
private readonly List<PagerLink
> _pagerLinks =
           
new List<PagerLink
>();
 
   
public PagerBuilder(string
urlTemplate)
    {
        _urlTemplate = urlTemplate;
    }
 
   
public string PagerClass { get; set
; }
 
   
public void AddPage(string title, int
pageNo)
    {
        AddPage(title, pageNo,
string
.Empty);
    }
 
   
public void AddPage(string title, int
pageNo,
                       
string
itemClass)
    {
       
var link = new PagerLink
        {
            PageNo = pageNo,
            Title = title,
            Class = itemClass
        };
        _pagerLinks.Add(link);
    }
 
   
public override string
ToString()
    {
       
var builder = new StringBuilder
();
        builder.Append(
"<div"
);
 
       
if (!string
.IsNullOrEmpty(PagerClass))
        {
            builder.Append(
" class=\""
);
            builder.Append(PagerClass);
            builder.Append(
"\""
);
        }
        builder.Append(
">"
);
 
       
foreach (var link in
_pagerLinks)
        {
            builder.Append(
"<a href=\""
);
            builder.AppendFormat(_urlTemplate, link.PageNo);
            builder.Append(
"\""
);
 
           
if (!string
.IsNullOrEmpty(link.Class))
            {
                builder.Append(
" class=\""
);
                builder.Append(link.Class);
                builder.Append(
"\""
);
            }
 
            builder.Append(
">"
);
            builder.Append(link.Title);
            builder.Append(
"</a>"
);
        }
 
        builder.Append(
"</div>"
);
 
       
return builder.ToString();
    }
}

To use pager in views I created extension method called SimplePager for HtmlHelper class. Here is my extension method.

public static string SimplePager(this HtmlHelper helper, 
   
int currentPage, int pageCount, string
urlTemplate,
   
string
pagerClass)
{
   
if
(currentPage < 0) currentPage = 1;
   
if
(pageCount < 0) pageCount = 0;
 
   
var pager = new PagerBuilder
(urlTemplate);
    pager.PagerClass = pagerClass;
 
   
if
(currentPage > 1)
    {
        pager.AddPage(
"&lt;&lt;"
, 1);
        pager.AddPage(
"&lt;"
, 1);
    }
 
   
var start = Math
.Max(currentPage - 2, 1);
   
var end = Math
.Min(pageCount, currentPage + 2);
 
   
for (var
i = start; i <= end; i++)
    {
       
if
(i == currentPage)
            pager.AddPage(i.ToString(), i,
"current"
);
       
else
            pager.AddPage(i.ToString(), i);
    }
 
   
if
(currentPage < pageCount)
    {
        pager.AddPage(
"&gt;"
, currentPage + 1);
        pager.AddPage(
"&gt;&gt;"
, pageCount);
    }
 
   
return pager.ToString();
}

It needs current page index and page count to generate pager. You must also provide pager class name and URL-template.

<%= Html.SimplePager(Model.CurrentPage, Model.PageCount, 
                     "/contacts/page/{0}", "pager")
%>

As you can see from example above you can use your model to provide pager with current page and page count. In my case it is okay because repository behind this view returns me paged results so I have no problems with getting current page index and page count.

Currently my pager looks like this after very short playing with styles. Not very nice but it works and some design dude who helps me out can easily make it look very nice.

ASP.NET MVC pager

Feel free to use and modify my code. If you have questions or suggestions then please drop  your comment here. Happy paging! :)

Liked this post? Empower your friends by sharing it!

Gunnar Peipman

Gunnar Peipman is ASP.NET, Azure and SharePoint fan, Estonian Microsoft user group leader, blogger, conference speaker, teacher, and tech maniac. Since 2008 he is Microsoft MVP specialized on ASP.NET.

    14 thoughts on “Simple pager for ASP.NET MVC

    • February 22, 2010 at 6:52 am
      Permalink

      You can replace hardcode string “/contacts/page/{0}” with Url.Action(“Index”, “Contacts”, new {page = “{0}”})

    • February 23, 2010 at 7:13 am
      Permalink

      Thanks for feedback! Never seen your code before, Jeff, but it does same thing. Just a little bit different implementation.

    • November 2, 2010 at 11:23 am
      Permalink

      Hi can u give me the sample code

    • November 9, 2010 at 2:30 pm
      Permalink

      Thx for paging. Very simple & nice issue :)

    • December 28, 2010 at 6:56 am
      Permalink

      thnx alot greate work best regards
      mohammed

    • February 11, 2011 at 1:16 pm
      Permalink

      Thanks for this valuable information but while i am running i am getting compilation error. can u help me plz.
      error is:

    • August 10, 2011 at 9:13 pm
      Permalink

      I’m a newbie to MVC, but the code above is outputting a string of the path. It’s not actually creating the required links. Am I doing something wrong?

    • August 10, 2011 at 9:24 pm
      Permalink

      Please disregard my note above… I figured it out! Amazing script, man. Thank you soo much.

    • December 6, 2011 at 9:27 pm
      Permalink

      Am I missing something or do you not specify anywhere the TotalRecordCount and without specifying that, how do you figure out how many pages to create?

    • December 6, 2011 at 10:11 pm
      Permalink

      My mistake, I was thinking “PageCount” was “itemsPerpage” not “Total number of Pages”

      I am dumb lol

    • December 13, 2011 at 10:11 pm
      Permalink

      I can’t get the HTML helper extension to be recognized as a method of the Html object in the view. I’m using ASP.NET MVC 4 and I’m using razor. Any ideas?

    • March 8, 2012 at 12:23 pm
      Permalink

      Now I want to change all of my websites to ASP.NET MVC… I just looking for paging last week. Today I got.
      Thanks..

    • December 17, 2015 at 5:56 am
      Permalink

      Hello Sir,

      Hope you are doing well.

      My name is Rajesh Patel and I am from india. I have been reading your blog since last 3 years. It really improves my knowledge in web technologies.

      Could you please mail me source code for pager functionality.

      Thanks

    Leave a Reply

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