Click here to Skip to main content
15,867,308 members
Articles / Web Development / ASP.NET
Article

Pagination Class for ASP.NET MVC

Rate me:
Please Sign up or sign in to vote.
4.38/5 (17 votes)
15 Aug 2008CPOL3 min read 104.5K   6.4K   37   13
A class for creating different types of pagination link in ASP.NET MVC.
pagination.jpg

Introduction

I was looking for a pagination class to use in ASP.NET MVC. I found ASP.NET MVC: PagedList<T> and ASP.NET MVC - Pagination View User Control. But I wanted an easier and customizable pagination class. I have developed many projects using the CodeIgniter framework and that time I found their pagination class is better and easier to use. So, I have decided to prepare a pagination class like this for ASP.NET MVC.

Using the Code

Controller

In your controller, to get your current (i.e. selected) page number page put this code snippet.

C#
string pageString = "";

try
{
    pageString = Request.Url.Segments[3];
}
catch (Exception)
{
    pageString = null;
}

int page = (String.IsNullOrEmpty(pageString)) ? 1 : Int32.Parse(pageString);

Here 3 is the segment which holds the page number. It can vary as per your URL.

Then use the pagination class as shown in the following example.

C#
Pagination pagination = new Pagination();

pagination.BaseUrl      = "/Users/List/";
pagination.TotalRows    = totalRows;
pagination.CurPage      = page;
pagination.PerPage      = 10;

string pageLinks = pagination.GetPageLinks();

int start   = (page - 1) * pagination.PerPage;
int offset  = pagination.PerPage;

In BaseUrl you can write a full path like http://www.sitename.com/Controller/Action/ or relative path like /Controller/Action/. Here start is the number from which row should be counted and offset is the number of rows that should be returned. totalRows is the total number of rows.

Now you can use this pageLinks string which is the generated page link.

Next, set your data in the ViewData like the following.

C#
ViewData["title"]       = "Pagination in Asp.Net Mvc";
ViewData["totalRows"]   = totalRows;
ViewData["result"]      = result;
ViewData["pageLinks"]   = pageLinks;

Here, totalRows is the total number of rows and result is the desired resultset.

View

In view page, you can show the page link as follows:

C#
<% if ((string)ViewData["pageLinks"] != "")
   { %>

   <%= ViewData["pageLinks"] %>
   <br /><br />
<% } %>

Model

You can create a model and make two methods to get total rows and the data from table using LINQ, as shown in the following example.

public int GetTotalUsers()
{
    return new MyDataContext().Users.Count();
}

public List<User> GetUsers(int start, int offset)
{
    var users = new MyDataContext().Users.Skip(start)
                                         .Take(offset);

    return users.ToList();
}

Configuration Settings

General Properites
BaseUrlFull or relative URL to the controller/action (Mandatory).
TotalRowsTotal number of rows in your resultset (Mandatory).
CurPageCurrent page number, default 1 (Mandatory).
PerPageNumber of items you want to show per page (Optional).
NumLinksNumber of "digit" links before and after the current page number (Optional).
ItemTypeItem type enumeration value (Optional).
Link Properites
FirstLinkThe text to be shown in the "first" link on the left.
NextLinkThe text to be shown in the "next" page link.
PrevLinkThe text to be shown in the "previous" page link.
LastLinkThe text to be shown in the "last" link on the right.
Tag Properties
FullTagOpenThe opening tag placed on the left side of the entire result.
FullTagCloseThe closing tag placed on the right side of the entire result.
FirstTagOpenThe opening tag for the "first" link.
FirstTagCloseThe closing tag for the "first" link.
LastTagOpenThe opening tag for the "last" link.
LastTagCloseThe closing tag for the "last" link.
CurTagOpenThe opening tag for the "current" link.
CurTagCloseThe closing tag for the "current" link.
NextTagOpenThe opening tag for the "next" link.
NextTagCloseThe closing tag for the "next" link.
PrevTagOpenThe opening tag for the "previous" link.
PrevTagCloseThe closing tag for the "previous" link.
NumTagOpenThe opening tag for the "digit" link.
NumTagCloseThe closing tag for the "digit" link.
ItemTagOpenThe opening tag for the "Item".
ItemTagCloseThe closing tag for the "Item".

You can set configuration settings in three ways.

  1. Set as regular property is set. Example:
    objPagination.PerPage  = 10;
    objPagination.PrevLink = "Prev";
    objPagination.NextLink = "Next";
  2. Put a Pagination.xml file in Content folder and create object of Pagination class as:
    C#
    Pagination objPagination = new Pagination(true);

    Pagination.xml file should be as following pattern as example.

    XML
    <?xml version="1.0" encoding="utf-8" ?>
    <Pagination>
        <NumLinks><![CDATA[5]]></NumLinks>
        <FullTagOpen><![CDATA[<p class='pagination'>]]></FullTagOpen>
    
        <FullTagClose><![CDATA[</p>]]></FullTagClose>
        <CurTagOpen><![CDATA[<span class='current'>]]></CurTagOpen>
        <CurTagClose><![CDATA[</span>]]></CurTagClose>
    
    </Pagination>
  3. Create any XML file like the above Pagination.xml file and call the method LoadPaginationXml with the file full path as argument. Example:
    C#
    objPagination.LoadPaginationXml("C:\\MyProject\\MyPagination.xml");

Different Types of Pagination

By this pagination class you can build different types of page links for your page. Just call the method GetPageLinks with your desired PaginationType as an argument. Example:

C#
objPagination.GetPageLinks(PaginationType.FirstPreviousNextLastItemRight);

You can display item set or item type as follows:

C#
objPagination.ItemType = ItemTypes.Page;

Conclusion

I think thats enough to use this pagination class easily. Bye for this time.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Bangladesh Bangladesh
Software Engineer, Bangladesh.

Comments and Discussions

 
QuestionThis is a good article to know how to do pagination class for ASP.NET mvc Pin
Member 1040443918-Nov-13 9:02
Member 1040443918-Nov-13 9:02 
QuestionEdit compoment pageLink? Pin
cuonghd1-Aug-13 4:51
cuonghd1-Aug-13 4:51 
QuestionI need to Hide Next and Prev Button. How can i do that Pin
Trung Dũng9-Jul-13 0:15
Trung Dũng9-Jul-13 0:15 
Pls help. I think It's no need to show Prev and Next button. But I don't know how to do this.
GeneralMy vote of 5 Pin
Member 776842615-Jan-13 22:04
Member 776842615-Jan-13 22:04 
GeneralMy vote of 4 Pin
congnthc14-Sep-12 5:19
congnthc14-Sep-12 5:19 
QuestionError in Example Pin
Ragesh S9-Feb-12 18:20
Ragesh S9-Feb-12 18:20 
Generalhey, where is the db of the sample project? Pin
PatoOrange13-May-11 5:42
PatoOrange13-May-11 5:42 
GeneralDatabase error Pin
DeepakRohilla1317-Sep-10 0:30
professionalDeepakRohilla1317-Sep-10 0:30 
GeneralMvcPager is another choice Pin
Webdiyer23-Feb-10 19:49
Webdiyer23-Feb-10 19:49 
GeneralModified your class for post action Pin
PikesvillePaesano24-Jun-09 3:50
PikesvillePaesano24-Jun-09 3:50 
GeneralRe: Modified your class for post action Pin
Jahedur Rahman Chowdhury24-Jun-09 18:44
Jahedur Rahman Chowdhury24-Jun-09 18:44 
GeneralWell Done! You saved me tons of time. I put my own spin on it by creating a static method for calling the paging method. Pin
Pikesville Paesano11-Jun-09 17:19
Pikesville Paesano11-Jun-09 17:19 
GeneralRe: Well Done! You saved me tons of time. I put my own spin on it by creating a static method for calling the paging method. Pin
Jahedur Rahman Chowdhury11-Jun-09 20:54
Jahedur Rahman Chowdhury11-Jun-09 20:54 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.