Introduction
In this article, we will learn how we can implement paging and sorting in MVC. In this article for paging we will use PageList.MVC package which we will download from Nuget Package Manager. I will create one table using code first approach of Entity Framework.
The following step will explain to you how can we perform paging and sorting in MVC.
Firstly, open Visual Studio and create an MVC project by clicking File, New, Project or press CTRL + SHIFT + N Key together.
After clicking on New Project you will get one dialog box. From that dialog box go to installed template and Visual C# and then web and choose ASP.NET Web Application and give the name to your project. Press OK, also you can follow the below figure.
After clicking on OK button you will get one more dialog box where you have to select your project template so select project template as MVC with
No Authentication.
After completing the above steps your project will ready. Now By default your project will contain Home Controller. So, delete HomeController and Inside View folder you will get Home Folder so also Delete Home Folder from the project.
After deleting right click on the solution and download Entity Framework from the Nuget Package Manager. Here are the steps for getting Entity Framework package in your solution.
- Right click on project and click on Manage NuGet Packages.
- After that you will get one more dialog box. On that dialog box click on online and search for Entity Framework.
After installing entity framework in my project I am creating a new folder with name "Entities" and also adding one class inside that folder with the name "EmployeeMaster".
Because I am creating this project with code first approach I am creating the table with the name EmployeeMaster so I have added this class. I am writing the following code inside that class.
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.Linq;
- using System.Web;
-
- namespace PagingAndSorting.Entities
- {
- public class EmployeeMaster
- {
- [Key]
- public string ID { get; set; }
- [Required(ErrorMessage="Please Enter Employee Name")]
- public string Name { get; set; }
- [Required(ErrorMessage="Please Enter Phone Number")]
- public string PhoneNumber { get; set; }
- [Required(ErrorMessage="Please Enter Email")]
- public string Email { get; set; }
- [Required(ErrorMessage="Please Enter Salary")]
- public decimal Salary { get; set; }
- }
- }
After writing the above code in your project build your project once and go to the Modal folder and add a class with name
ApplicationDbContext.
Write the following code inside ApplicationDbContext class.
- using PagingAndSorting.Entities;
- using System;
- using System.Collections.Generic;
- using System.Data.Entity;
- using System.Linq;
- using System.Web;
-
-
- namespace PagingAndSorting.Models
- {
- public class ApplicationDbContext:DbContext
- {
- public ApplicationDbContext()
- : base("DefaultConnection")
- {
- }
- public DbSet<EmployeeMaster> Employees { get; set; }
- }
- }
After adding that code in
ApplicationDbContext class add connection string in web.config. I am adding the following connection string in my code.
- <connectionStrings>
- <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=EmployeeDb;Integrated Security=True;MultipleActiveResultSets=true" providerName="System.Data.SqlClient" />
- </connectionStrings>
Now to generate database and table open package manager console. You can open package manager console by performing the following steps.
- Click on Tools strip on Menu Bar.
- Select Library Package Manager.
- Then Select Package Manager Console.
After opening package manager console. Type the following command,
After completing this process one folder will be generated in your solution that one's name will be Migrations. There will be one file Configurations.cs. Open that file and inside Configuration class constructor set AutomaticMigrationsEnabled to true.
Configurations.cs
- namespace PagingAndSorting.Migrations
- {
- using System;
- using System.Data.Entity;
- using System.Data.Entity.Migrations;
- using System.Linq;
-
- internal sealed class Configuration : DbMigrationsConfiguration<PagingAndSorting.Models.ApplicationDbContext>
- {
- public Configuration()
- {
- AutomaticMigrationsEnabled = true;
- }
-
- protected override void Seed(PagingAndSorting.Models.ApplicationDbContext context)
- {
-
-
-
-
-
-
-
-
-
-
-
-
- }
- }
- }
Now open package manager console and firethe following command which will generate database and tables.
After generating database for performing paging you have to download
PagedList.MVC from NuGet Package manager, so go to the NuGet Package Manager and then install
PagedList.MVC.
Now add a controller with name EmployeeController and write the following code.
- using PagingAndSorting.Entities;
- using PagingAndSorting.Models;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using PagedList;
- namespace PagingAndSorting.Controllers
- {
- public class EmployeeController : Controller
- {
-
-
- public ActionResult Index(string sortOrder, string CurrentSort, int? page)
- {
- ApplicationDbContext db = new ApplicationDbContext();
- int pageSize = 10;
- int pageIndex = 1;
- pageIndex = page.HasValue ? Convert.ToInt32(page) : 1;
- ViewBag.CurrentSort = sortOrder;
- sortOrder = String.IsNullOrEmpty(sortOrder) ? "Name" : sortOrder;
- IPagedList<EmployeeMaster> employees = null;
- switch (sortOrder)
- {
- case "Name":
- if (sortOrder.Equals(CurrentSort))
- employees = db.Employees.OrderByDescending
- (m => m.Name).ToPagedList(pageIndex, pageSize);
- else
- employees = db.Employees.OrderBy
- (m => m.Name).ToPagedList(pageIndex, pageSize);
- break;
- case "Email":
- if (sortOrder.Equals(CurrentSort))
- employees = db.Employees.OrderByDescending
- (m => m.Email).ToPagedList(pageIndex, pageSize);
- else
- employees = db.Employees.OrderBy
- (m => m.Email).ToPagedList(pageIndex, pageSize);
- break;
- case "Phone":
- if (sortOrder.Equals(CurrentSort))
- employees = db.Employees.OrderByDescending
- (m => m.PhoneNumber).ToPagedList(pageIndex, pageSize);
- else
- employees = db.Employees.OrderBy
- (m => m.PhoneNumber).ToPagedList(pageIndex, pageSize);
- break;
- case "Salary":
- if (sortOrder.Equals(CurrentSort))
- employees = db.Employees.OrderByDescending
- (m => m.Salary).ToPagedList(pageIndex, pageSize);
- else
- employees = db.Employees.OrderBy
- (m => m.Salary).ToPagedList(pageIndex, pageSize);
- break;
- case "Default":
- employees = db.Employees.OrderBy
- (m => m.Name).ToPagedList(pageIndex, pageSize);
- break;
- }
- return View(employees);
- }
-
-
- public ActionResult Add()
- {
- return View();
- }
-
- [HttpPost]
- [ValidateAntiForgeryToken]
- public ActionResult Add(EmployeeMaster emp)
- {
- emp.ID = Guid.NewGuid().ToString();
- ApplicationDbContext db = new ApplicationDbContext();
- db.Employees.Add(emp);
- db.SaveChanges();
- return RedirectToAction("Index");
- }
- }
- }
Now add two views, One for adding some Employee and second for Views Employee and Paging and Sorting. I am adding a View for Adding Employee with name Add
. And write the following code in Add View.
- @model PagingAndSorting.Entities.EmployeeMaster
-
- @{
- ViewBag.Title = "Add Employee";
- }
-
- <h2>Add</h2>
-
-
- @using (Html.BeginForm())
- {
- @Html.AntiForgeryToken()
-
- <div class="form-horizontal">
- <h4>EmployeeMaster</h4>
- <hr />
- @Html.ValidationSummary(true)
- <div class="form-group">
- @Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.Name)
- @Html.ValidationMessageFor(model => model.Name)
- </div>
- </div>
-
- <div class="form-group">
- @Html.LabelFor(model => model.PhoneNumber, new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.PhoneNumber)
- @Html.ValidationMessageFor(model => model.PhoneNumber)
- </div>
- </div>
-
- <div class="form-group">
- @Html.LabelFor(model => model.Email, new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.Email)
- @Html.ValidationMessageFor(model => model.Email)
- </div>
- </div>
-
- <div class="form-group">
- @Html.LabelFor(model => model.Salary, new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.Salary)
- @Html.ValidationMessageFor(model => model.Salary)
- </div>
- </div>
-
- <div class="form-group">
- <div class="col-md-offset-2 col-md-10">
- <input type="submit" value="Create" class="btn btn-default" />
- </div>
- </div>
- </div>
- }
-
- <div>
- @Html.ActionLink("Back to List", "Index")
- </div>
-
- @section Scripts {
- @Scripts.Render("~/bundles/jqueryval")
- }
And for Viewing list of Employee we have Index Controller so I am adding view with name
Index
. Write the following code for Index View.
- @model PagedList.IPagedList<PagingAndSorting.Entities.EmployeeMaster>
- @using PagedList.Mvc;
- @{
- ViewBag.Title = "Employee List";
- Layout = "~/Views/Shared/_Layout.cshtml";
- }
- <style>
- table {
- width: 100%;
- }
- table tr td{
- border: 2px solid black;
- text-align: center;
- word-wrap: break-word;
- }
-
- table tr:hover {
- background-color:#000;
- color:#fff;
- }
- table tr th {
- border: 2px solid black;
- text-align: center;
- background-color: #fff;
- color: #000;
- }
- </style>
- <h2>Employee List</h2>
-
- @using (Html.BeginForm())
- {
- <table>
- <tr>
- <th>
- @Html.ActionLink("Employee Name", "Index",
- new { sortOrder = "Name", CurrentSort = ViewBag.CurrentSort })
- </th>
- <th>
- @Html.ActionLink("Email", "Index",
- new { sortOrder = "Email", CurrentSort = ViewBag.CurrentSort })
- </th>
- <th>
- @Html.ActionLink("PhoneNumber", "Index",
- new { sortOrder = "Phone", CurrentSort = ViewBag.CurrentSort })
- </th>
- <th>
- @Html.ActionLink("Salary", "Index",
- new { sortOrder = "Salary", CurrentSort = ViewBag.CurrentSort })
- </th>
- </tr>
- @foreach (var item in Model)
- {
- <tr>
- <td>
- @Html.DisplayFor(modelItem => item.Name)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.Email)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.PhoneNumber)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.Salary)
- </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>
- }
Now I am changing Default URL for my Application in Route.Config.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using System.Web.Routing;
-
- namespace PagingAndSorting
- {
- public class RouteConfig
- {
- public static void RegisterRoutes(RouteCollection routes)
- {
- routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
-
- routes.MapRoute(
- name: "Default",
- url: "{controller}/{action}/{id}",
- defaults: new { controller = "Employee", action = "Index", id = UrlParameter.Optional }
- );
- }
- }
- }
And I am changing in Menu Bar under
_Layout.cshtml
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>@ViewBag.Title - My ASP.NET Application</title>
- @Styles.Render("~/Content/css")
- @Scripts.Render("~/bundles/modernizr")
- </head>
- <body>
- <div class="navbar navbar-inverse navbar-fixed-top">
- <div class="container">
- <div class="navbar-header">
- <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- </button>
- @Html.ActionLink("Employee Master", "Index", "Employee", null, new { @class = "navbar-brand" })
- </div>
- <div class="navbar-collapse collapse">
- <ul class="nav navbar-nav">
- <li>@Html.ActionLink("View Employee", "Index", "Employee")</li>
- <li>@Html.ActionLink("Add Employee ", "Add", "Employee")</li>
- </ul>
- </div>
- </div>
- </div>
- <div class="container body-content">
- @RenderBody()
- <hr />
- <footer>
- <p>© @DateTime.Now.Year - Employee Master</p>
- </footer>
- </div>
-
- @Scripts.Render("~/bundles/jquery")
- @Scripts.Render("~/bundles/bootstrap")
- @RenderSection("scripts", required: false)
- </body>
- </html>
Output:
Add Employee
List of Employee With Paging and Sorting
Complete Demo
Note: You can download this article code from the following
link.
Read more articles on ASP.NET: