Paging, Searching And Sorting In ASP.NET MVC 5

Introduction

From my explanation in my CRUD in ASP.NET MVC 5 article, you are now able to do basic CRUD operations MVC applications. This article explains how to do sorting, searching and paging in a MVC 5 application with Entity Framework 6 in Visual Studio 2013.

In that context we'll perform the paging and sorting for the Student entity and it'll be displayed in the Student's Index page. In the following article you will see how sorting works by clicking the headings. The headings are the links to show the sorted data.

So, let's proceed with the following sections:

  • Perform Sorting
  • Perform Searching
  • Perform Paging

Perform Sorting

Now in this section we will do the sorting of the Student entity. Please use the following procedure to do that.

Adding Sorting Functionality in Controller

Step 1 

Open the StudentController.cs file and replace the Index() method with the code below,

  1. public ActionResult Index(string Sorting_Order)  
  2. {  
  3.     ViewBag.SortingName = String.IsNullOrEmpty(Sorting_Order) ? "Name_Description" : "";  
  4.     ViewBag.SortingDate = Sorting_Order == "Date_Enroll" ? "Date_Description" : "Date";  
  5.     var students = from stu in db.Students select stu;  
  6.     switch (Sorting_Order)  
  7.     {  
  8.         case "Name_Description":  
  9.         students = students.OrderByDescending(stu=> stu.FirstName);  
  10.         break;  
  11.         case "Date_Enroll":  
  12.         students = students.OrderBy(stu => stu.EnrollmentDate);  
  13.         break;  
  14.         case "Date_Description":  
  15.         students = students.OrderByDescending(stu => stu.EnrollmentDate);  
  16.         break;  
  17.         default:  
  18.         students = students.OrderBy(stu => stu.FirstName);  
  19.         break;  
  20.     }  
  21.     return View(students.ToList());  
  22. }  

In the code above, the Sorting_Order parameter is responsible for getting the value from the query string in the URL. The parameter is a string and it is either a "Name" or a "Date". By default the sorting order is ascending.

The students are displayed as an ascending order the first time by their First Name. There are two variables of ViewBag used here for configuring the column heading hyperlinks with the appropriate query string values.

Adding Heading Hyperlinks in View

Step 2

Open the Views\Student\Index.cshtml page and modify it with the highlighted code below, 

  1. <p>  
  2.     @Html.ActionLink("Create New""Create")  
  3. </p>  
  4. <table class="table">  
  5.     <tr>  
  6.         <th>  
  7.             @Html.ActionLink("First Name""Index"new { Sorting_Order = ViewBag.SortingName })  
  8.         </th>  
  9.         <th>  
  10.             Last Name  
  11.         </th>  
  12.         <th>  
  13.             @Html.ActionLink("Enrollment Date""Index"new { Sorting_Order = ViewBag.SortingDate })  
  14.         </th>  
  15.         <th></th>  
  16.     </tr>   
  17. @foreach (var item in Model) {  

Step 3

Run the app and open Students. 

Apply Sorting in MVC 5

Step 4

Now click on the First Name (heading) and you'll see the descending order of data. 

Sorted Values in MVC 5

Searching

To do the searching in the application we need to add a TextBox to enter the searching credentials and using button, we can show the corresponding record. So, let's proceed with the steps below.

Adding Searching Functionality in Controller

Step 1

Open the StudentController.cs file and modify the Index() method with the highlighted code below, 

  1. public ActionResult Index(string Sorting_Order, string Search_Data)  
  2. {  
  3.     ViewBag.SortingName = String.IsNullOrEmpty(Sorting_Order) ? "Name_Description" : "";  
  4.     ViewBag.SortingDate = Sorting_Order == "Date_Enroll" ? "Date_Description" : "Date";  
  5.    
  6.     var students = from stu in db.Students select stu;  
  7.     {  
  8.         students = students.Where(stu => stu.FirstName.ToUpper().Contains(Search_Data.ToUpper())  
  9.             || stu.LastName.ToUpper().Contains(Search_Data.ToUpper()));  
  10.     }  
  11.     switch (Sorting_Order)  
  12.     {  
  13.         case "Name_Description":  
  14.         students = students.OrderByDescending(stu=> stu.FirstName);  
  15.         break;  
  16.         case "Date_Enroll":  
  17.         students = students.OrderBy(stu => stu.EnrollmentDate);  
  18.         break;  
  19.         case "Date_Description":  
  20.         students = students.OrderByDescending(stu => stu.EnrollmentDate);  
  21.         break;  
  22.         default:  
  23.         students = students.OrderBy(stu => stu.FirstName);  
  24.         break;  
  25.     }  
  26.    
  27.     return View(students.ToList());  
  28. }  

In the code above, we've added the Search_Data parameter and the LINQ statements. The where clause finds and selects only those student with a first name or last name containing the Search_Data value and the record is displayed in the Index view.

Adding Searching Button in View

Step 2

Open the Views\Student\Index.cshtml page and modify it with the highlighted code below,

  1. <p>  
  2.     @Html.ActionLink("Create New""Create")  
  3. </p>  
  4.    
  5. @using (Html.BeginForm())  
  6. {  
  7.     <p>  
  8.         Search Name: @Html.TextBox("Search_Data", ViewBag.FilterValue as string)  
  9.         <input type="submit" value="Find" />  
  10.     </p>  
  11. }  
  12.    
  13. <table class="table">  

Step 3

Run the app and open Students and enter the value to search for.

Searching Record in MVC

The searched record,

Searched Record in MVC

You can also notice that the URL doesn't contain the searching value, in other words you cannot bookmark this page.

Perform Paging

We perform paging here by adding the NuGet Package named PagedList.Mvc. We add the links for paging in our Student\Index.cshtml. This NuGet Package is one of many good paging and sorting packages for ASP.NET MVC programming.

Adding NuGet Package

We install the PagedList.Mvc NuGet Package in the application that will automatically add a PagedList package. It has the PagedList collection type and extension methods for the Iqueryable and IEnumerable collections to provide the paging. This NuGet Package is used to show the paging buttons.

Step 1: Open the Package Manager Console from the "Tools" -> "Library Package Manager".

Step 2: Enter the following command

Install-Package PagedList.Mvc

Packge Mamanger Console in MVC

Adding Paging Functionality

Step 3: Open the StudentController.cs file and the following namespace:

  1. using PagedList;  

Step 4: Modify the Index() with the highlighted code below:

  1. public ActionResult Index(string Sorting_Order, string Search_Data, string Filter_Value, int? Page_No)  
  2. {  
  3.     ViewBag.CurrentSortOrder = Sorting_Order;  
  4.     ViewBag.SortingName = String.IsNullOrEmpty(Sorting_Order) ? "Name_Description" : "";  
  5.     ViewBag.SortingDate = Sorting_Order == "Date_Enroll" ? "Date_Description" : "Date";  
  6.    
  7.     if (Search_Data != null)  
  8.     {  
  9.         Page_No = 1;  
  10.     }  
  11.     else  
  12.     {  
  13.         Search_Data = Filter_Value;  
  14.     }  
  15.    
  16.     ViewBag.FilterValue = Search_Data;  
  17.    
  18.     var students = from stu in db.Students select stu;  
  19.    
  20.     if (!String.IsNullOrEmpty(Search_Data))  
  21.     {  
  22.         students = students.Where(stu => stu.FirstName.ToUpper().Contains(Search_Data.ToUpper())  
  23.             || stu.LastName.ToUpper().Contains(Search_Data.ToUpper()));  
  24.     }  
  25.     switch (Sorting_Order)  
  26.     {  
  27.         case "Name_Description":  
  28.         students = students.OrderByDescending(stu=> stu.FirstName);  
  29.         break;  
  30.         case "Date_Enroll":  
  31.         students = students.OrderBy(stu => stu.EnrollmentDate);  
  32.         break;  
  33.         case "Date_Description":  
  34.         students = students.OrderByDescending(stu => stu.EnrollmentDate);  
  35.         break;  
  36.         default:  
  37.         students = students.OrderBy(stu => stu.FirstName);  
  38.         break;  
  39.     }  
  40.    
  41.     int Size_Of_Page = 4;  
  42.     int No_Of_Page = (Page_No ?? 1);  
  43.     return View(students.ToPagedList(No_Of_Page, Size_Of_Page));  

If you do not click on any paging or sorting link then the parameters value will be null.

Adding Paging Links in View

Step 5: Open the Views\Student\Index.cshtml page and modify it with the highlighted code below:

  1. @model PagedList.IPagedList<Vag_Infotech.Models.Student>  
  2. @using PagedList.Mvc;  
  3. <link href="~/Content/PagedList.css" rel="stylesheet" />  
  4.    
  5. @{  
  6.     ViewBag.Title = "Students";  
  7. }  
  8.    
  9. <h2>Students</h2>  
  10.    
  11. <p>  
  12.     @Html.ActionLink("Create New""Create")  
  13. </p>  
  14.    
  15. @using (Html.BeginForm("Index""Student", FormMethod.Get))  
  16. {  
  17.     <p>  
  18.         Search Name: @Html.TextBox("Search_Data", ViewBag.FilterValue as string)  
  19.         <input type="submit" value="Find" />  
  20.     </p>  
  21. }  
  22.    
  23. <table class="table">  
  24.     <tr>  
  25.         <th>  
  26.             @Html.ActionLink("First Name""Index"new { Sorting_Order = ViewBag.SortingName, Filter_Value = ViewBag.FilterValue })  
  27.         </th>  
  28.         <th>  
  29.             Last Name  
  30.         </th>  
  31.         <th>  
  32.             @Html.ActionLink("Enrollment Date""Index"new { Sorting_Order = ViewBag.SortingDate, Filter_Value = ViewBag.FilterValue })  
  33.         </th>  
  34.         <th></th>  
  35.     </tr>  
  36.    
  37. @foreach (var item in Model) {  
  38.     <tr>  
  39.         <td>  
  40.             @Html.DisplayFor(modelItem => item.FirstName)  
  41.         </td>  
  42.         <td>  
  43.             @Html.DisplayFor(modelItem => item.LastName)  
  44.         </td>  
  45.         <td>  
  46.             @Html.DisplayFor(modelItem => item.EnrollmentDate)  
  47.         </td>  
  48.         <td>  
  49.             @Html.ActionLink("Edit""Edit"new { id=item.ID }) |  
  50.             @Html.ActionLink("Details""Details"new { id=item.ID }) |  
  51.             @Html.ActionLink("Delete""Delete"new { id=item.ID })  
  52.         </td>  
  53.     </tr>  
  54. }  
  55.    
  56. </table>  
  57. <br />  
  58. Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount  
  59. @Html.PagedListPager(Model, Page_No =>Url.Action("Index",  
  60.     new { Page_No, Sorting_Order= ViewBag.CurrentSortOrder, Filter_Value = ViewBag.FilterValue }))   

We've added the @model statement that specifies that the view now gets a PagedList object instead of a List object. The using statement is used to access the PagedList.Mvc that is useful for accessing the paging buttons.

The PagedListPager helps to provide a number of options that is helpful for customization including URLs and styling.

Step 6: Run the application.

Apply Paging in MVC

In the preceding screenshot I've clicked on 2.

Step 7: Now search for a string.

Paging in MVC

Summary

This article showed how to do sorting, searching and paging in ASP.NET MVC Web Applications with the Entity Framework. Thanks for reading.


Similar Articles