博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[转]Paging, Searching and Sorting in ASP.Net MVC 5
阅读量:5058 次
发布时间:2019-06-12

本文共 8998 字,大约阅读时间需要 29 分钟。

本文转自:

 

Introduction

From my explanation in my  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.

 

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:

 

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.

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

Packge Mamanger Console in 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.

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.

 

 

 

转载于:https://www.cnblogs.com/freeliver54/p/3729148.html

你可能感兴趣的文章
设置虚拟机虚拟机中fedora上网配置-bridge连接方式(图解)
查看>>
HEVC播放器出炉,迅雷看看支持H.265
查看>>
[置顶] Android仿人人客户端(v5.7.1)——人人授权访问界面
查看>>
Eclipse 调试的时候Tomcat报错启动不了
查看>>
【安卓5】高级控件——拖动条SeekBar
查看>>
ES6内置方法find 和 filter的区别在哪
查看>>
Android入门之文件系统操作(二)文件操作相关指令
查看>>
Android实现 ScrollView + ListView无滚动条滚动
查看>>
java学习笔记之String类
查看>>
UVA 11082 Matrix Decompressing 矩阵解压(最大流,经典)
查看>>
jdk从1.8降到jdk1.7失败
查看>>
一些关于IO流的问题
查看>>
mongo备份操作
查看>>
8 -- 深入使用Spring -- 3...1 Resource实现类InputStreamResource、ByteArrayResource
查看>>
硬件笔记之Thinkpad T470P更换2K屏幕
查看>>
一个关于vue+mysql+express的全栈项目(六)------ 聊天模型的设计
查看>>
【知识库】-数据库_MySQL 的七种 join
查看>>
.net 写文件上传下载webservice
查看>>
noSQL数据库相关软件介绍(大数据存储时候,必须使用)
查看>>
iOS开发——缩放图片
查看>>