Objective
In the previous section we did the following as a basic query page. In this section we add sort, search, and paging functionality to this page.
Sort
You can see from the Address bar that this page calls the index Action under the company controller. So let's start by opening the CompanyController.cs file under the Controllers folder and writing the following code:
1 using System.Linq; 2 using SYSTEM.WEB.MVC; 3 using Slarkinc.dal; 4 using System; 5 6 Namespace Slarkinc.controllers 7 {8 public class Companycontroller:controller 9 {$ private company Context db = new Companycontext (); Public ViewResult Index (string sortOrder) {VIEWBAG.F Irstnamesortparm = String.IsNullOrEmpty (sortOrder)? "First_desc": ""; viewbag.lastnamesortparm = SortOrder = = "Last"? " Last_desc ":" Last "; the var workers = from W in db. WORKERS16 Select w;17 switch (sortOrder) _desc ": Workers = workers. OrderByDescending (w = w.firstname); break;22 case "Last_desc": 23 Workers = workers. OrderByDescending (w = w.lastname); break;25 case "Last": + W Orkers = workers. (w = w.laStname) break;28 default:29 workers = workers. (w = w.firstname); break;31}32 return View (workers. ToList ()); 33}34}35}
Line 11th, the parameter of the Index Action sortorder the information used to pass to the controller ordering. The SortOrder has 4 possible values. These 4 values are represented by a switch of 17 to 31 rows: The case statement. If it is First_desc, the FirstName is arranged in reverse order with orderbydescending. In the case of Last_desc, the LastName is arranged in reverse order. If it is last, the order of the LastName is ordered by the ordering function. If it is empty, it is arranged in FirstName order. The 第13-14 row uses ViewBag to store the currently arranged inverse permutation string, which is used to generate links in the view. 第15-16 rows, select the data to sort from the database using LINQ to Entity. The 32nd row of sorted data is passed to view in the form of a list.
In the corresponding view file ~\views\company\index.cshtml, modify the header portion of the table, as shown in the code below.
<tr><th> @Html. ActionLink ("First Name", "Index", new {SortOrder = viewbag.firstnamesortparm}) </th><th> @Html. ActionLink ("Last Name", "Index", new {SortOrder = viewbag.lastnamesortparm}) </th><th> @Html. displaynamefor (model = model. SEX) </th><th> @Html. displaynamefor (model = model. Rating) </th></tr>
The yellow part is the modified code. We changed the previous plain Text header to a hyperlink, and the linked parameters were obtained from the viewbag. Click the link to get the sort effect that is reversed from the current sort.
View this page from your browser. Then click on the LastName link, then follow the above code will generate the following page:
The parameter sortorder is last, and the table is sorted in LastName order.
Search
The General Query page will have a search function to help us see the page we want. Let's implement this feature.
or starting with the controller, the code for the Index action is written as follows:
1 Public ViewResult Index (string sortOrder, String searchstring) 2 {3 Viewbag.firstnamesortparm = String.isnulloremp Ty (sortOrder)? "First_desc": ""; 4 Viewbag.lastnamesortparm = SortOrder = = "Last"? "Last_desc": "Last"; 5 var workers = from W in db. Workers 6 Select W; 7 if (!string. IsNullOrEmpty (searchstring)) 8 {9 workers = workers. Where (w = w.firstname.contains (searchstring) ten | | w.lastname.contains (searchstring)); 1 1}12 switch (sortOrder), "first_desc": Workers = workers. OrderByDescending (w = w.firstname); break;17 case "last_desc": Workers = WORKERS.O Rderbydescending (w = w.lastname), break;20 case "last": Workers = workers. (w = w.lastname); break;23 default:24 workers = workers. (w = w.firstname); break;26 }27 return View (workers. ToList ()); 28}
The yellow part of the code above is what we added. Line 1th, SearchString passes the string to the controller for searching. On line 7th, the search is performed when the string is not empty. The search here uses the WHERE function in LINQ, which filters out qualifying data through a lambda expression. This condition is 9-10 rows of "or" connected two contains functions. The CONTAINS function indicates whether the string to which it belongs contains its argument string. The entire filter condition indicates that all fisrtname or LastName contain a record containing the filter string.
Here's a look at ~\views\company\index.cshtml's changes:
@using (Html.BeginForm ()) { <p> Find by name: @Html. TextBox ("SearchString", "", new {@class = " Form-control ", @Style =" Display:inline "}) @Html. Submit (" submit ") </p>}
Add the code to the table, which is a form that contains an input box and a Submit button, which submits the search string in the input box to the current controller to complete the search operation. One of the input boxes, added the class and style to its bootstrap beautification.
View this page through a browser, enter B in the search box and submit, and the following page appears:
You can see that the search result is FirstName or LastName contains all the records for B (not case).
Page out
Data queries are unavoidable for paging. Here we use a plug-in called Pagedlist to implement this function.
In the menu bar, select the package Management Console---Library package management, as shown below.
You will then see a Package Management Console window below the Visual Studio window. In which Install-package Pagedlist.mvc is entered. The pagedlist is automatically installed in the project. The window is shown below.
After the Paged List is installed, we begin to modify the code, starting with the controller:
1 using System.Linq; 2 using SYSTEM.WEB.MVC; 3 using Slarkinc.dal; 4 using System; 5 using Pagedlist; 6 7 Namespace Slarkinc.controllers 8 {9 public class Companycontroller:controller10 {one private company Context db = new Companycontext (); ViewResult Index (String sortOrder, String searchstring, String current Filter, int? Page) {Viewbag.currentsort = sortorder;15 Viewbag.firstnamesortparm = String.isnullor Empty (SortOrder)? "First_desc": ""; viewbag.lastnamesortparm = SortOrder = = "Last"? " Last_desc ":" Last "; + if (searchstring! = null) ~ {page = 1;20}21 Else22 {searchstring = currentfilter;24}25 viewbag.cur Rentfilter = searchstring;2627 var workers = from W in db. WORKERS28 Select W;29 if (!string. IsNullOrEmpty (searchstring)) 30 {workers = workers. Where (w = w.firstname.contains (searchstring) | | | w.lastname.contains (SEARCHST Ring),}34 switch (sortOrder) ("First_desc"): 37 Workers = workers. OrderByDescending (w = w.firstname); break;39 case "Last_desc": 40 Workers = workers. OrderByDescending (w = w.lastname); break;42 case "Last": W Orkers = workers. (w = w.lastname); break;45 default:46 workers = Worke Rs. (w = w.firstname); break;48}49 int pageSize = 3;50 I NT PageNumber = (page?? 1); return View (workers. Topagedlist (Pagenumber,pagesize)); 52}53}54}
The yellow mark is the part that needs to be changed. Line 5th, you need to refer to pagedlist. The 12th row of the CurrentFilter parameter is used to keep the search string from being lost while paging. The function of line 17th to 25th is that when a new string is searched, the current page is automatically changed to the first page, otherwise the current page will not change. The 第49-51 line sets 3 data per page, sets the number of pages, and sends the data as a list of view. Where (page? 1) means that if the page is null, the page is assigned a value of 1 otherwise, the page is not NULL then it is how much it is. So you can make the default page 1.
1 @model pagedlist.ipagedlist<slarkinc.models.worker> 2 @using pagedlist.mvc; 3 <link href= "~/content/pagedlist.css" rel= "stylesheet"/> 4 <br/> 5 @using (html.beginf ORM ("Index", "Company", Formmethod.get)) 6 {7 <p> 8 Find by name: @Html. TextBox ("SearchString", Viewbag.currentfilter as String, new {@class = "Form-control", @Style = "Display:inline"}) 9 @Html. Submit ("submit") </p>11}12 <table class= "table" >13 <t R>14 <th>15 @Html. ActionLink ("First Name", "Index", new {SortOrder = VIEWBAG.FIRSTNAMESORTPA RM}) </th>17 <th>18 @Html. ActionLink ("Last Name", "Index", new {SortOrder = Vi Ewbag.lastnamesortparm}) </th>20 <th>sex</th>21 <th>rating</th>22 </tr>23 @foreach (var item in Model) 24 {25 <tr>26 <td>27 @Html. displayfor (ModelItem = Item. FirstName) </td>29 <td>30 @Html. displayfor (ModelItem = Item. LastName) to </td>32 <td>33 @Html. displayfor (ModelItem = Item. Sex) </td>35 <td>36 @Html. displayfor (ModelItem = Item. Rating) PNs </td>38 </tr>39}40 </table>41 <br/>42 Page @ (Model.pagecount &L T Model.pagenumber? 0:model.pagenumber) of @Model. PageCount43 @Html. Pagedlistpager (Model, page = url.action ("Index", new {page, so Rtorder = viewbag.currentsort, CurrentFilter = Viewbag.currentfilter}))
The 1th line defines the model of the Pagedlist type. Line 2nd refers to Pagedlist. Line 3rd, introduced, pagedlist related CSS files, this file will be automatically saved to the project when the plugin is installed. The parameters of the BeginForm function in line 5th are changed, and the resulting form uses the Get method. The Get method displays the submitted parameters in the URL, so that the query parameters can be recorded by the URL, which makes it easy to show the results of your query by copying the URLs to others. Line 42nd is used to display the first few pages, a total of several pages. The 第43-44 line, which is used to generate buttons for each page.
Run this page and click the "2" button at the bottom of the page to go to page 2nd when the page comes out. The resulting page is as follows:
You can see the page buttons and pages at the bottom of the statistics, beautiful and generous.
Implementation of ASP. MVC4 Sorting Retrieval page