ASP.NET MVC – Pagination View User Control

Each website, content management system, blog and so on need "pagination". A never ending site with "foo-entries" is not very professional. Thats why i created for my ASP.NET MVC sample (a kigg / dotnetnuke similar page) a specific"Pagination View User Control"

In almost every "List" View I implemented my control:

image

image

The advantages of such an control:

- look and feel is on each page the same 
- changes are very easy to implement

In my sampel I use this CSS design.

Structure

image 

A typical MVC View User Control

Code

Pagination.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Pagination.ascx.cs" Inherits="Mvc2.Views.Shared.Pagination" %>
<ul class="pagination-clean">
    <% if (ViewData.HasPreviousPage)
        { %>
          <li class="previous"><a href="<%=ViewData.PageActionLink.Replace("%7Bpage%7D", (ViewData.PageIndex - 1).ToString())%>">« Previous</a></li>
     <% }
       else
        { %>
          <li class="previous-off">« Previous</li>
     <% } %>
                  
     <%for (int page = 1; page <= ViewData.TotalPages; page++)
        { 
        if (page == ViewData.PageIndex)
            { %>
              <li class="active"><%=page.ToString()%></li>
         <% }
        else
            { %>
              <li><a href="<%=ViewData.PageActionLink.Replace("%7Bpage%7D", page.ToString())%>"><%=page.ToString()%></a></li>
         <% }
        } 
              
       if (ViewData.HasNextPage)
            { %>
              <li class="next"><a href="<%=ViewData.PageActionLink.Replace("%7Bpage%7D", (ViewData.PageIndex + 1).ToString())%>">Next »</a></li>
         <% }
       else
            { %>
               <li class="next-off">Next »</li>
         <% } %>
</ul> 

Pagination.ascx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Mvc2.Views.Shared
{
    public class PaginationViewData
    {
        public int PageIndex { get; set; }
        public int TotalPages { get; set; }
        public int PageSize { get; set; }
        public int TotalCount { get; set; }
        public string PageActionLink { get; set; }
        public bool HasPreviousPage
        {
            get
            {
                return (PageIndex > 1);
            }
        }

        public bool HasNextPage
        {
            get
            {
                return (PageIndex * PageSize) <= TotalCount;
            }
        }
    }

    public partial class Pagination : System.Web.Mvc.ViewUserControl<PaginationViewData>
    {
        public Pagination()
        {

        }
    }
}

The ViewData is strongly typed by the PaginationViewData class.

How to use – Helper "PagedList"

It is very easy to use, if you are already use the PageList class:

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;

namespace Mvc2.Helpers
{
    public class PagedList<T> : List<T>
    {
        public PagedList(IQueryable<T> source, int index, int pageSize)
        {
            this.TotalCount = source.Count();
            this.PageSize = pageSize;
            this.PageIndex = index;
            this.AddRange(source.Skip((index - 1) * pageSize).Take(pageSize).ToList());

            int pageResult = 0;
            for (int counter = 1; pageResult < this.TotalCount; counter++)
            {
                pageResult = counter * this.PageSize;
                this.TotalPages = counter;
            }
        }

        public int TotalPages
        {
            get;
            set;
        }

        public int TotalCount
        {
            get;
            set;
        }

        public int PageIndex
        {
            get;
            set;
        }

        public int PageSize
        {
            get;
            set;
        }

        public bool HasPreviousPage
        {
            get
            {
                return (PageIndex > 1);
            }
        }

        public bool HasNextPage
        {
            get
            {
                return (PageIndex * PageSize) <= TotalCount;
            }
        }
    }

    public static class Pagination
    {
        public static PagedList<T> ToPagedList<T>(this IQueryable<T> source, int index, int pageSize)
        {
            return new PagedList<T>(source, index, pageSize);
        }

        public static PagedList<T> ToPagedList<T>(this IQueryable<T> source, int index)
        {
            return new PagedList<T>(source, index, 10);
        }
    }
}

The original code wrote Rob Conery – in my version is the first page the number 1, not 0 – a user could confused by the link to page number 0 ;)

How to use- in the view page

I render the control by using the in-build "Html.RenderUserControl" helper:

    <%=Html.RenderUserControl("~/Views/Shared/Pagination.ascx", new Mvc2.Views.Shared.PaginationViewData()
      {
          PageIndex = ViewData.EntryList.PageIndex,
          TotalPages = ViewData.EntryList.TotalPages,
          PageActionLink = Url.Action("List","Entry", new { category = ViewData.Category, page = "{page}"}),
          TotalCount = ViewData.EntryList.TotalCount,
          PageSize = ViewData.EntryList.PageSize
      }, null)%>

The properties of the control and of the PagedList are almost the same – only the "PageActionLink" is a specific property. The "PageActionLink" is the action Link to your controller – "/Management/Tag/2" route to your "Management"-Controller and "Tag"-ActionMethod with the page parameter. The "page = {page}" parameter is only a template for the real page number, which will be replaced in my control:

<li><a href="<%=ViewData.PageActionLink.Replace("%7Bpage%7D", page.ToString())%>"><%=page.ToString()%></a></li>

The URL helper method encode the { and } to %7B and %7D. I can´t explain it very well in english – one quick look in the source code (pagination.ascx) is very helpful ;)

Feel free to use it.

PS: English blogging is hard :/ ;)

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

About the author

Written by

Currently there is no additional info about this author.

  • http://www.squaredroot.com Troy Goode

    Nice work, Robert. This is something I (and I’m sure many other MVC developers) will use often.

    Oh, and your English was fine. =)

  • http://www.squaredroot.com Troy Goode

    Oh, and on another note, coincidentally I have made the same changes to Rob’s PagedList class as you have, but I think this is a bit better of a calculation for TotalPages:

    (excuse the formatting please)

    if( this.TotalCount > 0 )
    {
    this.TotalPages = (int)Math.Ceiling( (double)this.TotalCount / (double)this.PageSize );
    }
    else
    {
    this.TotalPages = 0;
    }

  • Pingback: Rob Conery's PagedList Class (Updated)

  • Pingback: Code-Inside gibts jetzt auch auf englisch… | Code-Inside Blog

  • Pingback: 47 ASP.NET MVC Resources to Rock Your Development - Craig Shoemaker

  • Pingback: ASP.NET MVC - Resources | Code-Inside Blog International

  • anonymous

    Can you post your controller code to complete this blog post so we can see how you are interacting with that. Sure, I can “imagine” sort of what you’re doing such as adding a page param in your action like you said, and imagine up your controller based on your route but would like to see the actual action, so I have a little more clear context.

    Would be a big help.

  • CK1

    Just wanted to say thanks – I’m new to MVC and this was a great help for paging! Cheers! :)

  • http://code-inside.de Robert Muehsig

    The controller code:
    You just have to pass a PagedList to your Viewdata like that:
    ListViewData list = new ListViewData();
    list.EntryList = EntryManager.LoadEntryCollectionByCategory(category).ToPagedList(page ?? 1);

    Hope this helps :)

  • http://www.linkedtraining.com.au Paul Linton

    I think that when you changed your page numbers to have a base of one rather than zero you need to change HasNextPage to be
    get { return (PageIndex * PageSize) < TotalCount; }

    Eg change <= to <

  • Marco Castro

    I’m trying with MVC Preview 3 but at the view form the system do not find ViewData.EntryList. Where is it?

  • http://code-inside.de Robert Muehsig

    You need a strongly typed ViewData class – EntryList is just a sample property in this ViewDataClass.
    Here is a nice blogpost about strongly typed ViewData classes:
    http://blog.codeville.net/2008/02/21/aspnet-mvc-making-strongly-typed-viewpages-more-easily/

  • Rui Heh

    Hi there, great code!!! Just want to address one small issue, when pages exceeds the default total page and next is clicked, it won’t show the next set of pages.

    Here is what I did. Hope if someone else has the same problem can make use of it.

    public int StartIndex
    {
    get
    {
    if (PageIndex > TotalPages)
    {
    return PageIndex – (PageIndex % TotalPages) + 1;
    }
    else
    return 1;
    }
    }

    and then, change the for loop to
    for (int page = ViewData.Model.StartIndex; page <= (ViewData.Model.StartIndex + ViewData.Model.TotalPages – 1); page++)

    If it is still not cleared. Email me royheh@comcast.net

  • http://blog.valenticabd.com Jahedur Rahman

    Nice Blog. :)

  • Pingback: A Tale of Valentica » Blog Archive » Pagination Class for ASP.NET MVC

  • Pingback: Silverlight: a generic Pagination Control at Guardian’s Home

  • gonzalo

    Hi, I’m having a hard time trying to find the RenderUserControl function.

    It’s not in HtmlHelper class

    Cheers

  • http://code-inside.de Robert Muehsig

    The “RenderUserControl” was in the Beta 3 days – maybe it has be renamed or you can find it in the MVCFuture bits (download @ codeplex.com/aspnet ).

  • gonzalo

    I finally found the solution. It’s called RenderPartial now. It takes the control name and ViewData as arguments.

    Thanks for answering!

    Gonzalo

  • Craig

    PagedList can use IEnumerable instead of IQueryable (more generic). Cheers!!

  • Craig

    Nevermind, I see the benefit of having an IQueryable ctor, but IEnumerable is still a good option to have ;-)

  • http://www.ozdorov.cn/ Buona

    Love the advice. Thank you.

  • http://n/a Josh

    Hello, I have a question about what my view page should inherit from. Im getting the following error:
    Parser Error Message: ‘Mvc2.Views.Shared.Pagination’ is not allowed here because it does not extend class ‘System.Web.Mvc.ViewPage’.

    Source Error:


    Line 1: <%@ Page Title="List Checkups" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="Mvc2.Views.Shared.Pagination" %>
    Line 2:
    Line 3: <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">

    Is there something I am leaving out? Ive added the Inherits=”Mvc2.Views.Shared.Pagination” At the top of my page, yet I still get this error. I am new to MVC. I would really like to get this working. Thanks for any help!

  • Pingback: [ASP.NET MVC] Paginazione con View User Control - Zaragon blog

  • Pingback: Rob Conery’s PagedList Class (Updated) « SquaredRoot

  • Nisar Khan

    can anybody post the sample downloadble code for testing? please?
    thanks.

  • Stefano

    please … link a downloadble example thanks

  • paolo izmoto

    Hello,

    This is very useful stuff.

    Thanks.

  • j

    I’m very new to mvc.  do you have a “test” solution that you can post? thanks!

  • ritz

    hello,

    i m not getting the viewdata on the user control,please tell me from where can I get this,but the post is good

  • Tho ta

    Everybody for me source sample of this topic?
    I very need source sample.
    Email: tavtho@gmail.com
    please?
    thank!!!

  • http://www.aspxsolutions.net Robert

    Leiber Robert – Vielen Dank fuer deine Poste! Jawohl ist Blogging auf Englisch sehr schwer!

  • Slongia

    Leaning ASP.NET MVC 2. Will appreciate if you post a link of working solution for download.

  • http://en.webdiyer.com Webdiyer

    I wrote a free asp.net mvc paging component called MvcPager,it support both basic url paging and Ajax paging using jQuery or MicrosoftAjax script library,you can view online demo and download a copy from http://en.webdiyer.com .

  • http://www.CustomerLiveSupport.com Moshe Dubman

    Thank you, I will be using this in my next project :)
    Vielen Dank und gruss aus Israel
    Moshe

  • http://en.webdiyer.com Webdiyer

    I wrote a free asp.net mvc paging component called MvcPager,it has more features and support Ajax paging using MicrosoftAjax or jQuery script library,you can view online demo and download it from http://en.webdiyer.com/mvcpager

  • Pingback: Creating an PagedList<T> that uses AJAX - Joseph Bulger IV

  • http://www.ibuzzs.com ibuzzs

    I’m learning mvc, it very nice tutorial, thanks!

  • http://www.nextiteration.de Ragims

    I dont understand how it works in controller.
    Can you please explain what you meen with:

    ListViewData list = new ListViewData();
    list.EntryList = EntryManager.LoadEntryCollectionByCategory(category).ToPagedList(page ?? 1);

    Thanks a lot and take care,
    Ragims

  • Mike

    Hi Robert,
    please share your code !

  • http://www.radpanama.com Carlos

    Don’t forget the css please , some people will like to have the css too.
    But this is great stuff by the way ;).

  • http://Website Example Code

    Do you send for me example code ? Thanks you

  • http://Website mac keylogger

    You have hit the mark. In it something is also to me your idea is

    pleasant. I suggest to take out for the general discussion.

  • http://Website wumeng

    Thank you I’m new to MVC and this was a great help for paging . I have a problem when I try to realize a sample program. It like this:

    Compilation Error

    Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

    Compiler Error Message: CS0570: ‘System.Web.Mvc.UserControlExtensions.RenderUserControl()’ is not supported by the language

    Source Error:

    Line 9:
    Line 10:
    Line 11: <%=Html.RenderUserControl("~/Views/Shared/Pagination.ascx", new MVC2.Views.Shared.PaginationViewData() {
    Line 12: PageIndex = Model.PageIndex,
    Line 13: TotalPages = Model.ToTalPages,

    Source File: c:\Documents and Settings\Administrator\桌面\MVC2\MVC2\Views\My\Index.aspx Line: 11

    Do you know what 's wrong with this?

  • Pingback: Pagination View User Control | aprabhakar2014

Recent Posts

  • HowTo: make out Retweet-counter in a random URL

      Twitter offers some interesting functions with the integration of the twitter button – every user can see how often the website has been retweeted and he can do the same with just one click. But of course the whole thing has his price: - The integration of the Twitter JavaScript makes the whole data […]

  • Time-controlled Azure WebJobs – Azure as easy as it get‘s

        While still in development the Azure WebJob SDK offers some cool features for procession and supply of information. A good example is the sample that observes the Azure Queue and processes an item as soon as it spots one.   Scenario: time-controlled activities – without queue and so on My scenario was quite […]

  • image2021-570x194_thumb.png
    HowTo: Create RSS Feeds with ASP.NET MVC

    I’ve already written about how to consume RSS or Atom Feeds with the SyndicationFeed (in German, sry) but todays post is about how to create or publish an own feed. Beside the age of the feed standard and the much defamation from Facebook, Twitter and Google on RSS/Atom I consider this easy to consume API […]

  • image1997-311x194_thumb.png
    How to access an Azure Website with the local IIS Manager

    Since the end of February it is possible to access an Azure Website with the IIS Manager. Although the Azure Management site offers some information there are more details visible at the IIS Manager. For the connection you will need an IIS Manager and the IIS Manager for Remote Administration Extension. It’s also possible to […]

  • image1929-570x143_thumb.png
    Create and validate own Json-Web-Tokens (JWTs)

    If you are interested in web authentication you probably have heard about JSON Web tokens (JWT). What is a JWT? Maybe I’m not using the correct security termination but however: JWTs are used to exchange claims between two systems. For example: You want to log on to a service (like Facebook, Twitter, etc.) and want […]

Support us