Published: October 30 2015

ASP.NET MVC - Pagination Example with Logic like Google

Example built with ASP.NET MVC

Other versions available:

This is an example of how to setup pagination logic similar to what you see in Google search results.

It's written in C# and ASP.NET MVC, but the pagination logic is pure C# and could easily be converted to other languages such as Javascript to run on NodeJS, PHP or Java etc. The front end pagination component in the example is styled using Bootstrap.

Here it is in action: (See on .NET Fiddle at https://dotnetfiddle.net/eOe3tv)


Google Pagination Logic

The logic in Google's pagination is as follows:

  • there are 10 page links shown at any time (e.g. 1 2 3 4 5 6 7 8 9 10) unless there are less than 10 total pages
  • the active link (current page) is in the 6th position, except for when the active link is below 6 or less than 4 from the last position


Here's what it looks like for each page if there are 15 total pages:

[1] 2 3 4 5 6 7 8 9 10
1 [2] 3 4 5 6 7 8 9 10
1 2 [3] 4 5 6 7 8 9 10
1 2 3 [4] 5 6 7 8 9 10
1 2 3 4 [5] 6 7 8 9 10
1 2 3 4 5 [6] 7 8 9 10
2 3 4 5 6 [7] 8 9 10 11
3 4 5 6 7 [8] 9 10 11 12
4 5 6 7 8 [9] 10 11 12 13
5 6 7 8 9 [10] 11 12 13 14
6 7 8 9 10 [11] 12 13 14 15
6 7 8 9 10 11 [12] 13 14 15
6 7 8 9 10 11 12 [13] 14 15
6 7 8 9 10 11 12 13 [14] 15
6 7 8 9 10 11 12 13 14 [15] 

While this looks pretty simple at first there's actually a bit of tricky logic to get it working correctly, particularly when the selected page is below 6 or less than 4 from the end, and also to cater for when there are more or less than 10 total pages.

To make the pagination logic reusable across different pages and projects, I packaged it up in a C# class called Pager.cs:

Pager.cs - Pagination Logic in C# like Google

public class Pager
{
	public Pager(int totalItems, int? page, int pageSize = 10)
	{
		// calculate total, start and end pages
		var totalPages = (int)Math.Ceiling((decimal)totalItems / (decimal)pageSize);
		var currentPage = page != null ? (int)page : 1;
		var startPage = currentPage - 5;
		var endPage = currentPage + 4;
		if (startPage <= 0)
		{
			endPage -= (startPage - 1);
			startPage = 1;
		}
		if (endPage > totalPages)
		{
			endPage = totalPages;
			if (endPage > 10)
			{
				startPage = endPage - 9;
			}
		}

		TotalItems = totalItems;
		CurrentPage = currentPage;
		PageSize = pageSize;
		TotalPages = totalPages;
		StartPage = startPage;
		EndPage = endPage;
	}

	public int TotalItems { get; private set; }
	public int CurrentPage { get; private set; }
	public int PageSize { get; private set; }
	public int TotalPages { get; private set; }
	public int StartPage { get; private set; }
	public int EndPage { get; private set; }
}

 


Need Some C# Help?

Search fiverr for freelance C# developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by