Gunnar Peipman's ASP.NET blog

ASP.NET, C#, SharePoint, SQL Server and general software development topics.

Sponsors

News

 
 
 
DZone MVB

Links

Social

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.

My ASP.NET MVC pages

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

Comments

ch.mvc said:

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

# February 22, 2010 1:52 AM

Jeff said:

# February 22, 2010 1:05 PM

DigiMortal said:

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

# February 23, 2010 2:13 AM

Hardik said:

Hi can u give me the sample code

# November 2, 2010 7:23 AM

FSoul said:

Thx for paging. Very simple & nice issue :)

# November 9, 2010 9:30 AM

mohammed said:

thnx alot greate work best regards

mohammed

# December 28, 2010 1:56 AM

Lekhya said:

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

error is:

# February 11, 2011 8:16 AM

Mark said:

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 5:13 PM

Mark said:

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

# August 10, 2011 5:24 PM

Jack said:

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 4:27 PM

Jack said:

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

I am dumb lol

# December 6, 2011 5:11 PM

Joe said:

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?

# December 13, 2011 5:11 PM

ShweRoom said:

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

Thanks..

# March 8, 2012 7:23 AM