Click here to Skip to main content
6,822,123 members and growing! (18,057 online)
Email Password   helpLost your password?
Web Development » ASP.NET » Utilities     Intermediate License: The Code Project Open License (CPOL)

Pagination Class for ASP.NET MVC

By Mohammad Jahedur Rahman

A class for creating different types of pagination link in ASP.NET MVC.
C#, Windows, .NET (.NET3.5), ASP.NET, Dev
Posted:15 Aug 2008
Views:11,919
Bookmarked:22 times
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
8 votes for this article.
Popularity: 3.33 Rating: 3.69 out of 5
2 votes, 25.0%
1

2

3
1 vote, 12.5%
4
5 votes, 62.5%
5
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.

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.

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.

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:

<% 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
BaseUrl Full or relative URL to the controller/action (Mandatory).
TotalRows Total number of rows in your resultset (Mandatory).
CurPage Current page number, default 1 (Mandatory).
PerPage Number of items you want to show per page (Optional).
NumLinks Number of "digit" links before and after the current page number (Optional).
ItemType Item type enumeration value (Optional).
Link Properites
FirstLink The text to be shown in the "first" link on the left.
NextLink The text to be shown in the "next" page link.
PrevLink The text to be shown in the "previous" page link.
LastLink The text to be shown in the "last" link on the right.
Tag Properties
FullTagOpen The opening tag placed on the left side of the entire result.
FullTagClose The closing tag placed on the right side of the entire result.
FirstTagOpen The opening tag for the "first" link.
FirstTagClose The closing tag for the "first" link.
LastTagOpen The opening tag for the "last" link.
LastTagClose The closing tag for the "last" link.
CurTagOpen The opening tag for the "current" link.
CurTagClose The closing tag for the "current" link.
NextTagOpen The opening tag for the "next" link.
NextTagClose The closing tag for the "next" link.
PrevTagOpen The opening tag for the "previous" link.
PrevTagClose The closing tag for the "previous" link.
NumTagOpen The opening tag for the "digit" link.
NumTagClose The closing tag for the "digit" link.
ItemTagOpen The opening tag for the "Item".
ItemTagClose The 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:
    Pagination objPagination = new Pagination(true);

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

    <?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:
    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:

objPagination.GetPageLinks(PaginationType.FirstPreviousNextLastItemRight);

You can display item set or item type as follows:

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)

About the Author

Mohammad Jahedur Rahman


Member
Senior Software Engineer in Brain Station-23, Bangladesh.
Occupation: Software Developer (Senior)
Company: Brain Station-23
Location: Bangladesh Bangladesh

Other popular ASP.NET articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 4 of 4 (Total in Forum: 4) (Refresh)FirstPrevNext
GeneralModified your class for post action PinmembervbJammin4:50 24 Jun '09  
GeneralRe: Modified your class for post action PinmemberMohammad Jahedur Rahman19:44 24 Jun '09  
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. PinmemberPikesville Paesano18:19 11 Jun '09  
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. PinmemberMohammad Jahedur Rahman21:54 11 Jun '09  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

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

PermaLink | Privacy | Terms of Use
Last Updated: 15 Aug 2008
Editor: Sean Ewington
Copyright 2008 by Mohammad Jahedur Rahman
Everything else Copyright © CodeProject, 1999-2010
Web21 | Advertise on the Code Project