本文转自:http://www.c-sharpcorner.com/UploadFile/4b0136/perform-paging-searching-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:

public ActionResult Index(string Sorting_Order)
{
    ViewBag.SortingName = String.IsNullOrEmpty(Sorting_Order) ? "Name_Description" : "";
    ViewBag.SortingDate = Sorting_Order == "Date_Enroll" ? "Date_Description" : "Date";

var students = from stu in db.Students select stu;

switch (Sorting_Order)
    {
        case "Name_Description":
        students = students.OrderByDescending(stu=> stu.FirstName);
        break;
        case "Date_Enroll":
        students = students.OrderBy(stu => stu.EnrollmentDate);
        break;
        case "Date_Description":
        students = students.OrderByDescending(stu => stu.EnrollmentDate);
        break;
        default:
        students = students.OrderBy(stu => stu.FirstName);
        break;
    }
    return View(students.ToList());
}

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:

<p>
    @Html.ActionLink("Create New", "Create")
</p>

<table class="table">
    <tr>
        <th>
            @Html.ActionLink("First Name", "Index", new { Sorting_Order = ViewBag.SortingName })
        </th>
        <th>
            Last Name
        </th>
        <th>
            @Html.ActionLink("Enrollment Date", "Index", new { Sorting_Order = ViewBag.SortingDate })
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {

Step 3: Run the app and open Students.

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

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:

public ActionResult Index(string Sorting_Order, string Search_Data)
{
    ViewBag.SortingName = String.IsNullOrEmpty(Sorting_Order) ? "Name_Description" : "";
    ViewBag.SortingDate = Sorting_Order == "Date_Enroll" ? "Date_Description" : "Date";
 
    var students = from stu in db.Students select stu;

    {
        students = students.Where(stu => stu.FirstName.ToUpper().Contains(Search_Data.ToUpper())
            || stu.LastName.ToUpper().Contains(Search_Data.ToUpper()));
    }
    switch (Sorting_Order)
    {
        case "Name_Description":
        students = students.OrderByDescending(stu=> stu.FirstName);
        break;
        case "Date_Enroll":
        students = students.OrderBy(stu => stu.EnrollmentDate);
        break;
        case "Date_Description":
        students = students.OrderByDescending(stu => stu.EnrollmentDate);
        break;
        default:
        students = students.OrderBy(stu => stu.FirstName);
        break;
    }
 
    return View(students.ToList());
}
 

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:

<p>
    @Html.ActionLink("Create New", "Create")
</p>
 
@using (Html.BeginForm())
{
    <p>
        Search Name: @Html.TextBox("Search_Data", ViewBag.FilterValue as string)
        <input type="submit" value="Find" />
    </p>
}
 
<table class="table">

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

The searched record:

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 ourStudent\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

Adding Paging Functionality

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

using PagedList;

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

public ActionResult Index(string Sorting_Order, string Search_Data, string Filter_Value, int? Page_No)
{
    ViewBag.CurrentSortOrder = Sorting_Order;
    ViewBag.SortingName = String.IsNullOrEmpty(Sorting_Order) ? "Name_Description" : "";
    ViewBag.SortingDate = Sorting_Order == "Date_Enroll" ? "Date_Description" : "Date";
 
    if (Search_Data != null)
    {
        Page_No = 1;
    }
    else
    {
        Search_Data = Filter_Value;
    }
 
    ViewBag.FilterValue = Search_Data;
 
    var students = from stu in db.Students select stu;
 
    if (!String.IsNullOrEmpty(Search_Data))
    {
        students = students.Where(stu => stu.FirstName.ToUpper().Contains(Search_Data.ToUpper())
            || stu.LastName.ToUpper().Contains(Search_Data.ToUpper()));
    }
    switch (Sorting_Order)
    {
        case "Name_Description":
        students = students.OrderByDescending(stu=> stu.FirstName);
        break;
        case "Date_Enroll":
        students = students.OrderBy(stu => stu.EnrollmentDate);
        break;
        case "Date_Description":
        students = students.OrderByDescending(stu => stu.EnrollmentDate);
        break;
        default:
        students = students.OrderBy(stu => stu.FirstName);
        break;
    }
 
    int Size_Of_Page = 4;
    int No_Of_Page = (Page_No ?? 1);
    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:

@model PagedList.IPagedList<Vag_Infotech.Models.Student>
@using PagedList.Mvc;
<link href="~/Content/PagedList.css" rel="stylesheet" />
 
@{
    ViewBag.Title = "Students";
}
 
<h2>Students</h2>
 
<p>
    @Html.ActionLink("Create New", "Create")
</p>
 
@using (Html.BeginForm("Index", "Student", FormMethod.Get))
{
    <p>
        Search Name: @Html.TextBox("Search_Data", ViewBag.FilterValue as string)
        <input type="submit" value="Find" />
    </p>

}
 
<table class="table">
    <tr>
        <th>
            @Html.ActionLink("First Name", "Index", new { Sorting_Order = ViewBag.SortingName, Filter_Value = ViewBag.FilterValue })
        </th>
        <th>
            Last Name
        </th>
        <th>
            @Html.ActionLink("Enrollment Date", "Index", new { Sorting_Order = ViewBag.SortingDate, Filter_Value = ViewBag.FilterValue })
        </th>
        <th></th>
    </tr>
 
@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.FirstName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.LastName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.EnrollmentDate)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
            @Html.ActionLink("Details", "Details", new { id=item.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ID })
        </td>
    </tr>
}
 
</table>
<br />
Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount
@Html.PagedListPager(Model, Page_No =>Url.Action("Index",
    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 Listobject. 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.

In the preceding screenshot I've clicked on 2.

Step 7: Now search for a string.

Summary

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

[转]Paging, Searching and Sorting in ASP.Net MVC 5的更多相关文章

  1. Csharp:Paging Sorting Searching In ASP.NET MVC 5

    http://www.c-sharpcorner.com/UploadFile/0c1bb2/sorting-paging-searching-in-Asp-Net-mvc-5/ https://dz ...

  2. [转]Sorting, Filtering, and Paging with the Entity Framework in an ASP.NET MVC Application (3 of 10)

    本文转自:http://www.asp.net/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/sorting-fi ...

  3. ASP.NET MVC WebGrid – Performing true AJAX pagination and sorting 【转】

    ASP.NET MVC WebGrid – Performing true AJAX pagination and sorting FEBRUARY 27, 2012 14 COMMENTS WebG ...

  4. ASP.NET MVC with Entity Framework and CSS一书翻译系列文章之目录导航

    ASP.NET MVC with Entity Framework and CSS是2016年出版的一本比较新的.关于ASP.NET MVC.EF以及CSS技术的图书,我将尝试着翻译本书以供日后查阅. ...

  5. 【jqGrid for ASP.NET MVC Documentation】.学习笔记.2.jqGrid Model-View-Controller 分离

    1 基本 分离代码 和 描述 ,在ASP.NET MVC 应用程序中是非常重要的.因此,jqGrid 的 mvc 模式使用一个共同的网格安装设置,包括 Model ,Controller 和 View ...

  6. ASP.NET MVC 5 實作 GridView 分頁

    本文用 ASP.NET MVC 5 實作一個 GridView,功能包括: 分頁(paging).關鍵字過濾(filtering).排序(sorting).AJAX 非同步執行,外觀上亦支援 Resp ...

  7. ASP.NET MVC搭建项目后台UI框架—5、Demo演示Controller和View的交互

    目录 ASP.NET MVC搭建项目后台UI框架—1.后台主框架 ASP.NET MVC搭建项目后台UI框架—2.菜单特效 ASP.NET MVC搭建项目后台UI框架—3.面板折叠和展开 ASP.NE ...

  8. ASP.NET MVC搭建项目后台UI框架—6、客户管理(添加、修改、查询、分页)

    目录 ASP.NET MVC搭建项目后台UI框架—1.后台主框架 ASP.NET MVC搭建项目后台UI框架—2.菜单特效 ASP.NET MVC搭建项目后台UI框架—3.面板折叠和展开 ASP.NE ...

  9. ASP.NET MVC搭建项目后台UI框架—7、统计报表

    ASP.NET MVC搭建项目后台UI框架—1.后台主框架 ASP.NET MVC搭建项目后台UI框架—2.菜单特效 ASP.NET MVC搭建项目后台UI框架—3.面板折叠和展开 ASP.NET M ...

随机推荐

  1. spring boot file上传

    用Spring Boot写读取Excel文件小工具的时候遇到的一些小坑已经填平,复制即可满足普通的文件上传功能POI方面只需一个包,其他通用包工程中一般都会带TIPS:前端为了扩展我用ajax异步请求 ...

  2. Ubuntu系统备份工具大全(官方整理推荐)

    其实官方在系统备份这块已经有Wiki整理和收集各类实用的工具.以下是翻译自官方Wiki的部分文档: 备份工具  wiki文档实用程序 工具 界面 格式类型 Raw/File 支持 远程 增量 差异 自 ...

  3. OCP知识点讲解 之 队列、资源与锁:RHCA|OCM|CCIE RedHat大中华地区前50位RHCA系统架构师:叶绍琛

      一.队列与共享资源 共享资源可以被多个会话.进程同时访问,因此它的访问需要保护.Oracle中,除了PGA,所有的东西(包括内存.磁盘.CPU.表.索引.事务等等,种类太多,一概用东西两字来代表) ...

  4. 学习swift从青铜到王者之Swift集合数据类型03

    1 数组的定义 var array1 = [,,,] var array2: Array = [,,,] var array3: Array<Int> = [,,,] var array4 ...

  5. NA交换②

    虚拟局域网VLAN的核心目的:     将一个大的网络划分为小的网络,也称为网络分片(Segementation):一个VLAN对应着一个广播域,最好对应一个网络子网(为VLAN间的路由作准备).   ...

  6. jQuery异步框架探究1:jQuery._Deferred方法

    jQuery异步框架应用于jQuery数据缓存模块.jQuery ajax模块.jQuery事件绑定模块等多个模块,是jQuery的基础功能之中的一个.实际上jQuery实现的异步回调机制能够看做ja ...

  7. SpringMVC之application-context.xml,了解数据库相关配置

    上一篇SpringMVC之web.xml让我们了解到配置一个web项目的时候,怎样做基础的DispatcherServlet相关配置.作为SpringMVC上手的第一步.而application-co ...

  8. 程序中使用cocostudio移植到android手机须要的若干配置过程

    首先在解决方式下加入现有项: libCocosStudio.vcxproj E$uVS5Sbv! WL:0n"BExtensions.vcxproj libGUI.vcxproj 然后在pr ...

  9. python2.x里unicode错误问题

    import sys reload(sys) sys.setdefaultencoding('utf8')

  10. finger的使用

    finger命令用来查询一台主机上的登录账号的信息,通常会显示用户名.主目录.停滞时间.登录时间.登录Shell等信息,使用权限为所有用户. 安装 sudo apt-get install finge ...