Paging and Sorting in MVC 4

This article explains how to implement paging and sorting in MVC using Entity Framework Paged List Library.

  1. Getting Started
     
  2. Create a new project; first open Visual Studio 2012
     
  3. Then go to "File" => "New" => "Project..."
     
  4. Select Web in installed templates
     
  5. Select ASP.NET MVC 4 Web Application
     
  6. Enter the Name and choose the location
     
  7. Click OK

Please refer to this article to bind the Entity Framework and load data into views:

http://www.c-sharpcorner.com/UploadFile/raj1979/unit-testing-in-mvc-4-using-entity-framework/

Now let's add a new assembly using Manage Nuget Packages and type.

img1.jpg

Image 1.

And install it.

This is my Model class:

 

  1. public partial class Employee   
  2. {  
  3.     public int EmployeeID { getset; }  
  4.     public string LastName { getset; }  
  5.     public string FirstName { getset; }  
  6.     public int DepartmentID { getset; }  
  7.     public decimal Salary { getset; }  
  8.     public System.DateTime HireDate { getset; }  
  9. }  

 

This is my repository class:

 

  1. public class EmployeeRepository : IEmployeeRepository, IDisposable  
  2. {  
  3.     private PagingDataEntities2 context;  
  4.     public EmployeeRepository(PagingDataEntities2 context)  
  5.     {  
  6.         this.context = context;  
  7.     }  
  8.     public IEnumerable<Employee> GetEmployee()  
  9.     {  
  10.         return context.Employees.ToList();  
  11.     }  
  12.     public Employee GetEmployeeByID(int EmployeeID)  
  13.     {  
  14.         return context.Employees.Find(EmployeeID);  
  15.     }  
  16.     public void InsertEmployee(Employee employee)  
  17.     {  
  18.         context.Employees.Add(employee);  
  19.     }  
  20.     public void DeleteEmployee(int EmployeeID)  
  21.     {  
  22.         Employee employee = context.Employees.Find(EmployeeID);  
  23.         context.Employees.Remove(employee);  
  24.     }  
  25.     public void UpdateEmployee(Employee employee)  
  26.     {  
  27.         context.Entry(employee).State = EntityState.Modified;  
  28.     }  
  29.     public void Save()  
  30.     {  
  31.         context.SaveChanges();  
  32.     }  
  33.     private bool disposed = false;  
  34.     protected virtual void Dispose(bool disposing)  
  35.     {  
  36.         if (!this.disposed)  
  37.         {  
  38.             if (disposing)  
  39.             {  
  40.                 context.Dispose();  
  41.             }  
  42.         }  
  43.         this.disposed = true;  
  44.     }  
  45.     public void Dispose()  
  46.     {  
  47.         Dispose(true);  
  48.         GC.SuppressFinalize(this);  
  49.     }  
  50. }

This is the code for the IEmployeeRepository interface:

  1. public interface IEmployeeRepository : IDisposable  
  2. {  
  3.     IEnumerable<Employee> GetEmployee();  
  4.     Employee GetEmployeeByID(int EmployeeID);  
  5.     void InsertEmployee(Employee employee);  
  6.     void DeleteEmployee(int EmployeeID);  
  7.     void UpdateEmployee(Employee employee);  
  8.     void Save();  
  9. }   

Let's work on the controller now.

  1. public class EmployeeController : Controller  
  2. {  
  3.     private IEmployeeRepository employeeRepository;  
  4.     public EmployeeController()  
  5.     {  
  6.         this.employeeRepository = new EmployeeRepository(new PagingDataEntities2());  
  7.     }  
  8.     public EmployeeController(IEmployeeRepository employeeRepository)  
  9.     {  
  10.         this.employeeRepository = employeeRepository;  
  11.     }  
  12.     //  
  13.     // GET: /Employee/  
  14.     public ViewResult Index(string sortOrder, string currentFilter, string searchString, int? page)  
  15.     {  
  16.         ViewBag.CurrentSort = sortOrder;  
  17.         ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "Salery desc" : "";  
  18.         ViewBag.DateSortParm = sortOrder == "HireDate" ? "HireDate desc" : "HireDate";  
  19.         if (Request.HttpMethod == "GET")  
  20.         {  
  21.             searchString = currentFilter;  
  22.         }  
  23.         else  
  24.         {  
  25.             page = 1;  
  26.         }  
  27.         ViewBag.CurrentFilter = searchString;  
  28.         var employees = from s in employeeRepository.GetEmployee()  
  29.                        select s;  
  30.         if (!String.IsNullOrEmpty(searchString))  
  31.         {  
  32.             employees = employees.Where(s => s.LastName.ToUpper().Contains(searchString.ToUpper())  
  33.                                    || s.FirstName.ToUpper().Contains(searchString.ToUpper()));  
  34.         }  
  35.         switch (sortOrder)  
  36.         {  
  37.             case "Salery desc":  
  38.                 employees = employees.OrderByDescending(s => s.LastName);  
  39.                 break;  
  40.             case "HireDate":  
  41.                 employees = employees.OrderBy(s => s.HireDate);  
  42.                 break;  
  43.             case "HireDate desc":  
  44.                 employees = employees.OrderByDescending(s => s.HireDate);  
  45.                 break;  
  46.             default:  
  47.                 employees = employees.OrderBy(s => s.LastName);  
  48.                 break;  
  49.         }  
  50.         int pageSize = 10;  
  51.         int pageNumber = (page ?? 1);  
  52.         return View(employees.ToPagedList(pageNumber, pageSize));  
  53.     }  
  54.     //  
  55.     // GET: /Employee/Details/5  
  56.     public ViewResult Details(int id)  
  57.     {  
  58.         Employee employee = employeeRepository.GetEmployeeByID(id);  
  59.         return View(employee);  
  60.     }  
  61.     //  
  62.     // GET: /Employee/Create  
  63.     public ActionResult Create()  
  64.     {  
  65.         return View();  
  66.     }  
  67.     //  
  68.     // POST: /Employee/Create  
  69.     [HttpPost]  
  70.     public ActionResult Create(Employee employee)  
  71.     {  
  72.         try  
  73.         {  
  74.             if (ModelState.IsValid)  
  75.             {  
  76.                 employeeRepository.InsertEmployee(employee);  
  77.                 employeeRepository.Save();  
  78.                 return RedirectToAction("Index");  
  79.             }  
  80.         }  
  81.         catch (DataException)  
  82.         {  
  83.             //Log the error (add a variable name after DataException)  
  84.             ModelState.AddModelError("""Unable to save changes. Try again, and if the problem persists see your system administrator.");  
  85.         }  
  86.         return View(employee);  
  87.     }  
  88.     //  
  89.     // GET: /Employee/Edit/5  
  90.     public ActionResult Edit(int id)  
  91.     {  
  92.         Employee employee = employeeRepository.GetEmployeeByID(id);  
  93.         return View(employee);  
  94.     }  
  95.     //  
  96.     // POST: /Employee/Edit/5  
  97.     [HttpPost]  
  98.     public ActionResult Edit(Employee employee)  
  99.     {  
  100.         try  
  101.         {  
  102.             if (ModelState.IsValid)  
  103.             {  
  104.                 employeeRepository.UpdateEmployee(employee);  
  105.                 employeeRepository.Save();  
  106.                 return RedirectToAction("Index");  
  107.             }  
  108.         }  
  109.         catch (DataException)  
  110.         {  
  111.             //Log the error (add a variable name after DataException)  
  112.             ModelState.AddModelError("""Unable to save changes. Try again, and if the problem persists see your system administrator.");  
  113.         }  
  114.         return View(employee);  
  115.     }  
  116.     //  
  117.     // GET: /Employee/Delete/5  
  118.     public ActionResult Delete(int id, bool? saveChangesError)  
  119.     {  
  120.         if (saveChangesError.GetValueOrDefault())  
  121.         {  
  122.             ViewBag.ErrorMessage = "Unable to save changes. Try again, and if the problem persists see your system administrator.";  
  123.         }  
  124.         Employee employee = employeeRepository.GetEmployeeByID(id);  
  125.         return View(employee);  
  126.     }  
  127.     //  
  128.     // POST: /Employee/Delete/5  
  129.     [HttpPost, ActionName("Delete")]  
  130.     public ActionResult DeleteConfirmed(int id)  
  131.     {  
  132.         try  
  133.         {  
  134.             Employee employee = employeeRepository.GetEmployeeByID(id);  
  135.             employeeRepository.DeleteEmployee(id);  
  136.             employeeRepository.Save();  
  137.         }  
  138.         catch (DataException)  
  139.         {  
  140.             //Log the error (add a variable name after DataException)  
  141.             return RedirectToAction("Delete",  
  142.                 new System.Web.Routing.RouteValueDictionary {  
  143.             { "id", id },  
  144.             { "saveChangesError"true } });  
  145.         }  
  146.         return RedirectToAction("Index");  
  147.     }  
  148.     protected override void Dispose(bool disposing)  
  149.     {  
  150.         employeeRepository.Dispose();  
  151.         base.Dispose(disposing);  
  152.     }  
  153.  

Now add a View using the Razor View Engine and select a model class and scaffold template; see:

  1. @model PagedList.IPagedList<MvcPagingSorting.Models.Employee>  
  2. @{  
  3.     ViewBag.Title = "Employees";  
  4. }  
  5. <h2>Index</h2>  
  6. <p>  
  7.     @Html.ActionLink("Create New""Create")  
  8. </p>  
  9. @using (Html.BeginForm())  
  10. {  
  11.     <p>  
  12.         Search By Name : @Html.TextBox("SearchString", ViewBag.CurrentFilter as string)    
  13.         <input type="submit" value="Search" /></p>  
  14. }  
  15. <table>  
  16.     <tr>  
  17.         <th>  
  18.              @Html.Label("Last Name", ViewBag.CurrentFilter as string)  
  19.         </th>  
  20.         <th>  
  21.               @Html.Label("First Name", ViewBag.CurrentFilter as string)  
  22.         </th>  
  23.         <th>  
  24.             @Html.Label("Department ID", ViewBag.CurrentFilter as string)          
  25.         </th>  
  26.         <th>  
  27.             @Html.ActionLink("Salery""Index"new { sortOrder=ViewBag.NameSortParm, currentFilter=ViewBag.CurrentFilter })  
  28.         </th>  
  29.         <th>  
  30.             @Html.ActionLink("HireDate""Index"new { sortOrder=ViewBag.NameSortParm, currentFilter=ViewBag.CurrentFilter })  
  31.         </th>  
  32.         <th></th>  
  33.     </tr>  
  34. @foreach (var item in Model) {  
  35.     <tr>  
  36.         <td>  
  37.             @Html.DisplayFor(modelItem => item.LastName)  
  38.         </td>  
  39.         <td>  
  40.             @Html.DisplayFor(modelItem => item.FirstName)  
  41.         </td>  
  42.         <td>  
  43.             @Html.DisplayFor(modelItem => item.DepartmentID)  
  44.         </td>  
  45.         <td>  
  46.             @Html.DisplayFor(modelItem => item.Salary)  
  47.         </td>  
  48.         <td>  
  49.             @Html.DisplayFor(modelItem => item.HireDate)  
  50.         </td>  
  51.         <td>  
  52.             @Html.ActionLink("Edit""Edit"new { id=item.EmployeeID }) |  
  53.             @Html.ActionLink("Details""Details"new { id=item.EmployeeID }) |  
  54.             @Html.ActionLink("Delete""Delete"new { id=item.EmployeeID })  
  55.         </td>  
  56.     </tr>  
  57. }  
  58. <div>  
  59.     Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber)  
  60.     of @Model.PageCount  
  61.        
  62.     @if (Model.HasPreviousPage)  
  63.     {  
  64.         @Html.ActionLink("<<""Index"new { page = 1, sortOrder = ViewBag.CurrentSort, currentFilter=ViewBag.CurrentFilter  })  
  65.         @Html.Raw(" ");  
  66.         @Html.ActionLink("< Prev""Index"new { page = Model.PageNumber - 1, sortOrder = ViewBag.CurrentSort, currentFilter=ViewBag.CurrentFilter  })  
  67.     }  
  68.     else  
  69.     {  
  70.         @:<<  
  71.         @Html.Raw(" ");  
  72.         @:< Prev  
  73.     }  
  74.        
  75.     @if (Model.HasNextPage)  
  76.     {  
  77.         @Html.ActionLink("Next >""Index"new { page = Model.PageNumber + 1, sortOrder = ViewBag.CurrentSort, currentFilter=ViewBag.CurrentFilter  })  
  78.         @Html.Raw(" ");  
  79.         @Html.ActionLink(">>""Index"new { page = Model.PageCount, sortOrder = ViewBag.CurrentSort, currentFilter=ViewBag.CurrentFilter  })  
  80.     }  
  81.     else  
  82.     {  
  83.         @:Next >  
  84.         @Html.Raw(" ")  
  85.         @:>>  
  86.     }  
  87. </div>  
  88. </table> 

Now let's run the project to see the output:

img2.jpg

Image 2.

Let's search by name.

img3.jpg

Image 3.

Click on the paging link and see the query string.

img4.jpg

Image 4.

Click on the Salary and Hire Date columns to test sorting.

img5.jpg

Image 5.


Similar Articles