Hi friends, In this tutorial, I am going to show you how to implement Paging and Sorting in ASP.NET MVC using PageList. The PageList package installs a PageList collection type and extension methods for iQueryable and IEnumerable collections.

Paging and Sorting using PageList in ASP.NET MVC:

Let’s create a simple example that will illustrate you how to use PageList to implement paging and sorting in ASP.NET MVC. First of all, we need to create a table and insert records.

Create a Database and Table:

CREATE DATABASE [Debugonweb]
USE [Debugonweb]
GO

CREATE TABLE [dbo].[Employee](
[EmployeeID] [bigint] IDENTITY(1,1) NOT NULL,
[EmployeeName] [varchar](50) NULL,
[Salary] [float] NULL,
[Gender] [varchar](10) NULL,
[Address] [varchar](50) NULL,
[State] [varchar](50) NULL,
[City] [varchar](50) NULL,
[Status] [varchar](20) NULL,
CONSTRAINT [PK__Employee__3214EC274AA9A371] PRIMARY KEY CLUSTERED
(
[EmployeeID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

Insert Records:

USE [Debugonweb]
GO
SET IDENTITY_INSERT [dbo].[Employee] ON

GO
INSERT [dbo].[Employee] ([EmployeeID], [EmployeeName], [Salary], [Gender], [Address], [State], [City], [Status]) VALUES (1, N'Vinod', 50000, N'Male', N'Varanasi', N'UP', N'Varanasi', N'Active')
GO
INSERT [dbo].[Employee] ([EmployeeID], [EmployeeName], [Salary], [Gender], [Address], [State], [City], [Status]) VALUES (2, N'Manoj', 60000, N'Male', N'Varanasi', N'UP', N'Varanasi', N'Active')
GO
INSERT [dbo].[Employee] ([EmployeeID], [EmployeeName], [Salary], [Gender], [Address], [State], [City], [Status]) VALUES (3, N'Ansh', 30000, N'Male', N'Varanasi', N'UP', N'Varanasi', N'Active')
GO
INSERT [dbo].[Employee] ([EmployeeID], [EmployeeName], [Salary], [Gender], [Address], [State], [City], [Status]) VALUES (4, N'Ritesh', 2000, N'Male', N'Varanasi', N'UP', N'Varanasi', N'Active')
GO
INSERT [dbo].[Employee] ([EmployeeID], [EmployeeName], [Salary], [Gender], [Address], [State], [City], [Status]) VALUES (5, N'Vishwas', 15000, N'Male', N'Varanasi', N'UP', N'Varanasi', N'InActive')
GO
INSERT [dbo].[Employee] ([EmployeeID], [EmployeeName], [Salary], [Gender], [Address], [State], [City], [Status]) VALUES (6, N'Ansh', 50000, N'Male', N'Varanasi', N'UP', N'Varanasi', N'Active')
GO
INSERT [dbo].[Employee] ([EmployeeID], [EmployeeName], [Salary], [Gender], [Address], [State], [City], [Status]) VALUES (7, N'Varali', 50000, N'Male', N'Varanasi', N'UP', N'Varanasi', N'Active')
GO
INSERT [dbo].[Employee] ([EmployeeID], [EmployeeName], [Salary], [Gender], [Address], [State], [City], [Status]) VALUES (8, N'Nitin', 40000, N'Male', N'Varanasi', N'UP', N'Varanasi', N'Active')
GO
INSERT [dbo].[Employee] ([EmployeeID], [EmployeeName], [Salary], [Gender], [Address], [State], [City], [Status]) VALUES (9, N'Vikas', 3000, N'Male', N'Varanasi', N'UP', N'Varanasi', N'Active')
GO
INSERT [dbo].[Employee] ([EmployeeID], [EmployeeName], [Salary], [Gender], [Address], [State], [City], [Status]) VALUES (10, N'Ritwik', 50000, N'Male', N'Varanasi', N'UP', N'Varanasi', N'Active')
GO
INSERT [dbo].[Employee] ([EmployeeID], [EmployeeName], [Salary], [Gender], [Address], [State], [City], [Status]) VALUES (11, N'Arohi', 3000, N'Male', N'Varanasi', N'UP', N'Varanasi', N'InActive')
GO
SET IDENTITY_INSERT [dbo].[Employee] OFF
GO

CREATE ASP.NET MVC Project:

Step 1: Open Visual Studio and Create an ASP.NET Web Application called MVCPageListDemo

PageList

Step 2: Choose Empty template and check the MVC checkbox as shown in the below image.

PageList

Step 3: If you will not choose an empty solution and you will get a default empty solution with HomeController.in the Controller Folder. By default Entity Framework is downloaded as a package in the application folder. If your application does not contain Entity Framework package you can download the Entity Framework package by just following the steps:

Goto Tools>Library Package Manager>Package Manager Console and install Entity Framework packages using the following Command.

Install-Package EntityFramework -Version 6.2.0

Step 4: Now we need to create a Model for our application. Right Click on the Model folder and create a Model called Employee. Replace the following code.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace MVCPageListDemo.Models
{
[System.ComponentModel.DataAnnotations.Schema.Table("Employee")]
public class Employee
{
[Key]
public Int64 EmployeeID { get; set; }
public string EmployeeName { get; set; }
public string Gender { get; set; }
public double Salary { get; set; }
public string Address { get; set; }
public string State { get; set; }
public string City { get; set; }
public string Status { get; set; }


}
}

Step 5: Right Click on the Model folder and create a class called EmployeeDbContext. Write the following code in EmployeeDbContext class.

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace MVCPageListDemo.Models
{
public class EmployeeDbContext : DbContext
{
public DbSet<Employee> Employee { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer<EmployeeDbContext>(null);
base.OnModelCreating(modelBuilder);
}
}
}

Step 6: Don’t forget to add Connection String in Web.config with the name EmployeeDbContext 

<connectionStrings>
<add name="EmployeeDbContext" connectionString="data source=your-data-source;Initial Catalog=Debugonweb;integrated security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>

Replace your data source name in the above connection string.

Step 7: Right Click on the Controller folder and create a Controller called HomeController. Add an Index action method in the Controller class.

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



namespace MVCPageListDemo.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
}
}

Step 9: Now Install Page List Package by going to Tools>Library Package Manager>Package Manager Console and install Entity Framework packages using the following Command.

Install-Package PagedList.Mvc -Version 4.5.0

Step 9: Add the following namespaces in the Controller class.

using MVCPageListDemo.Models;
using PagedList;

Step 10: Now we need to instantiate EmployeeDbContext. Add the following code in HomeController.

EmployeeDbContext objEmployeeDbContext;

public HomeController()
{
objEmployeeDbContext= new EmployeeDbContext();
}

Step 11: Write the following code in the Index action method.

int pageSize = 5;
int pageIndex = 1;
pageIndex = page.HasValue ? Convert.ToInt32(page) : 1;

ViewBag.CurrentSort = sortOrder;

sortOrder = String.IsNullOrEmpty(sortOrder) ? "EmployeeID" : sortOrder;

IPagedList<Employee> lstEmployee = null;

switch (sortOrder)
{
case "EmployeeID":
if (sortOrder.Equals(CurrentSort))
lstEmployee = objEmployeeDbContext.Employee.OrderByDescending
(m => m.EmployeeID).ToPagedList(pageIndex, pageSize);
else
lstEmployee = objEmployeeDbContext.Employee.OrderBy
(m => m.EmployeeID).ToPagedList(pageIndex, pageSize);
break;
case "EmployeeName":
if (sortOrder.Equals(CurrentSort))
lstEmployee = objEmployeeDbContext.Employee.OrderByDescending
(m => m.EmployeeName).ToPagedList(pageIndex, pageSize);
else
lstEmployee = objEmployeeDbContext.Employee.OrderBy
(m => m.EmployeeName).ToPagedList(pageIndex, pageSize);
break;

case "Salary":
if (sortOrder.Equals(CurrentSort))
lstEmployee = objEmployeeDbContext.Employee.OrderByDescending
(m => m.Salary).ToPagedList(pageIndex, pageSize);
else
lstEmployee = objEmployeeDbContext.Employee.OrderBy
(m => m.Salary).ToPagedList(pageIndex, pageSize);
break;


case "State":
if (sortOrder.Equals(CurrentSort))
lstEmployee = objEmployeeDbContext.Employee.OrderByDescending
(m => m.State).ToPagedList(pageIndex, pageSize);
else
lstEmployee = objEmployeeDbContext.Employee.OrderBy
(m => m.State).ToPagedList(pageIndex, pageSize);
break;

case "City":
if (sortOrder.Equals(CurrentSort))
lstEmployee = objEmployeeDbContext.Employee.OrderByDescending
(m => m.City).ToPagedList(pageIndex, pageSize);
else
lstEmployee = objEmployeeDbContext.Employee.OrderBy
(m => m.City).ToPagedList(pageIndex, pageSize);
break;
 
case "Default":
lstEmployee = objEmployeeDbContext.Employee.OrderBy
(m => m.EmployeeID).ToPagedList(pageIndex, pageSize);
break;
}
return View(lstEmployee);

Complete code for Home Controller:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCPageListDemo.Models;
using PagedList;

namespace MVCPageListDemo.Controllers
{
public class HomeController : Controller
{
// GET: Home

EmployeeDbContext objEmployeeDbContext;

public HomeController()
{
objEmployeeDbContext = new EmployeeDbContext();
}
public ActionResult Index(string sortOrder, string CurrentSort, int? page)
{
int pageSize = 5;
int pageIndex = 1;
pageIndex = page.HasValue ? Convert.ToInt32(page) : 1;

ViewBag.CurrentSort = sortOrder;

sortOrder = String.IsNullOrEmpty(sortOrder) ? "EmployeeID" : sortOrder;

IPagedList<Employee> lstEmployee = null;

switch (sortOrder)
{
case "EmployeeID":
if (sortOrder.Equals(CurrentSort))
lstEmployee = objEmployeeDbContext.Employee.OrderByDescending
(m => m.EmployeeID).ToPagedList(pageIndex, pageSize);
else
lstEmployee = objEmployeeDbContext.Employee.OrderBy
(m => m.EmployeeID).ToPagedList(pageIndex, pageSize);
break;
case "EmployeeName":
if (sortOrder.Equals(CurrentSort))
lstEmployee = objEmployeeDbContext.Employee.OrderByDescending
(m => m.EmployeeName).ToPagedList(pageIndex, pageSize);
else
lstEmployee = objEmployeeDbContext.Employee.OrderBy
(m => m.EmployeeName).ToPagedList(pageIndex, pageSize);
break;

case "Salary":
if (sortOrder.Equals(CurrentSort))
lstEmployee = objEmployeeDbContext.Employee.OrderByDescending
(m => m.Salary).ToPagedList(pageIndex, pageSize);
else
lstEmployee = objEmployeeDbContext.Employee.OrderBy
(m => m.Salary).ToPagedList(pageIndex, pageSize);
break;


case "State":
if (sortOrder.Equals(CurrentSort))
lstEmployee = objEmployeeDbContext.Employee.OrderByDescending
(m => m.State).ToPagedList(pageIndex, pageSize);
else
lstEmployee = objEmployeeDbContext.Employee.OrderBy
(m => m.State).ToPagedList(pageIndex, pageSize);
break;

case "City":
if (sortOrder.Equals(CurrentSort))
lstEmployee = objEmployeeDbContext.Employee.OrderByDescending
(m => m.City).ToPagedList(pageIndex, pageSize);
else
lstEmployee = objEmployeeDbContext.Employee.OrderBy
(m => m.City).ToPagedList(pageIndex, pageSize);
break;
 
case "Default":
lstEmployee = objEmployeeDbContext.Employee.OrderBy
(m => m.EmployeeID).ToPagedList(pageIndex, pageSize);
break;
}
return View(lstEmployee);
}
}
}

Step 12: Right Click on the Index Action method and add a View called Index.cshtml. Write the following code in Index.cshtml page.

@model PagedList.IPagedList<MVCPageListDemo.Models.Employee>

@using PagedList.Mvc;
@{
ViewBag.Title = "Employee List";
 
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<h2>Employee List</h2>

@using (Html.BeginForm())
{
<table class="table table-striped">
<tr>
<th >
@Html.ActionLink("Employee ID", "Index",
new { sortOrder = "EmployeeID", CurrentSort = ViewBag.CurrentSort })
</th>
<th >
@Html.ActionLink("Employee Name", "Index",
new { sortOrder = "EmployeeName", CurrentSort = ViewBag.CurrentSort })
</th>
<th >
Gender
</th>
<th >
@Html.ActionLink("Salary", "Index",
new { sortOrder = "Salary", CurrentSort = ViewBag.CurrentSort })
</th>
<th >
Address
</th>

<th >
@Html.ActionLink("State", "Index",
new { sortOrder = "State", CurrentSort = ViewBag.CurrentSort })
</th>
<th >
@Html.ActionLink("City", "Index",
new { sortOrder = "City", CurrentSort = ViewBag.CurrentSort })
</th>
<th >
Status 
</th>

</tr>
@foreach (var item in Model)
{
<tr>
<td >
@Html.DisplayFor(modelItem => item.EmployeeID)
</td>
<td >
@Html.DisplayFor(modelItem => item.EmployeeName)
</td>
<td >
@Html.DisplayFor(modelItem => item.Gender)
</td>
<td >
@Html.DisplayFor(modelItem => item.Salary)
</td>
<td >
@Html.DisplayFor(modelItem => item.Address)
</td>
<td >
@Html.DisplayFor(modelItem => item.State)
</td>
<td >
@Html.DisplayFor(modelItem => item.City)
</td>
<td >
@Html.DisplayFor(modelItem => item.Status)
</td>
</tr>
}
</table>
<br />
<div id='Paging' style="text-align: center">
Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber)
of @Model.PageCount

@Html.PagedListPager(Model, page => Url.Action("Index", new { page }))
</div>
}

Run the application.

Output:

PageList

View More:

Conclusion:

I hope you would love this post. Please don’t hesitate to comment if you face any technical issue. Yoiur feedback, amd suggestions are always apprepricated.

Thank You.

Leave a Comment