MVC5 + EF6 + Bootstrap3 (11) sorting, search, paging, mvc5ef6

Source: Internet
Author: User
Tags actionlink

MVC5 + EF6 + Bootstrap3 (11) sorting, search, paging, mvc5ef6

Source: Slark. NET-blog Park http://www.cnblogs.com/slark/p/mvc5-ef6-bs3-get-started-pagedlist.html

Series of tutorials: MVC5 + EF6 + Bootstrap3

Previous section: MVC5 + EF6 + Bootstrap3 (10) Data Query page

Download source code: Click here to download

Directory
  • Preface
  • Sort
  • Search
  • Paging
  • End
Preface

In the previous section, we made the following basic query page. In this section, we add the sorting, search, and paging functions to this page.

Sort

From the address bar in, we can see that this page calls the Index Action under Company Controller. Therefore, we should first open the CompanyController. cs file in the Controllers folder and write 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     {10         private CompanyContext db = new CompanyContext();11         public ViewResult Index(string sortOrder)12         {13             ViewBag.FirstNameSortParm = String.IsNullOrEmpty(sortOrder) ? "first_desc" : "";14             ViewBag.LastNameSortParm = sortOrder == "last" ? "last_desc" : "last";15             var workers = from w in db.Workers16                         select w;17             }18             switch (sortOrder)19             {20                 case "first_desc":21                     workers = workers.OrderByDescending(w => w.FirstName);22                     break;23                 case "last_desc":24                     workers = workers.OrderByDescending(w => w.LastName);25                     break;26                 case "last":27                     workers = workers.OrderBy(w => w.LastName);28                     break;29                 default:30                     workers = workers.OrderBy(w => w.FirstName);31                     break;32             }33             return View(workers.ToList());34         }35     }36 }

The Index Action parameter sortOrder is used to pass the sorting information to the Controller. SortOrder has four possible values. These four values are reflected in switch... case statements in rows 18 to 32. If it is first_desc, use OrderByDescending to sort FirstName in reverse order. Last_desc is used to sort LastName in reverse order. If it is last, the LastName is ordered by the OrderBy function. If it is null, The FirstName is ordered. Row 13-14 uses Viewbag to store the reverse string of the current arrangement, which is used to generate links in the View. Line 15-16: Use Linq to Entity to select the data to be sorted from the database. 33rd rows of sorted data are passed to the View in the form of a List.

In the corresponding View File ~ In \ Views \ Company \ Index. cshtml, modify its header. The Code is as follows.

<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 header of the previous plain text to a hyperlink. The link parameters are obtained from ViewBag. Click the link to obtain the sorting result opposite to the current sorting result.

View this page in a browser. Click the "LastName" link. The following page is generated based on the code above:

 

If the sortOrder parameter is set to last, the table is ordered by lastName.

Search

Generally, the search function is available on the query page to help us view the desired page. Next we will implement this function.

Or from the Controller, the Index Action code is written as follows:

 1 public ViewResult Index(string sortOrder, string searchString) 2 { 3     ViewBag.FirstNameSortParm = String.IsNullOrEmpty(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)10                                 || w.LastName.Contains(searchString));11     }12     switch (sortOrder)13     {14         case "first_desc":15             workers = workers.OrderByDescending(w => w.FirstName);16             break;17         case "last_desc":18             workers = workers.OrderByDescending(w => w.LastName);19             break;20         case "last":21             workers = workers.OrderBy(w => w.LastName);22             break;23         default:24             workers = workers.OrderBy(w => w.FirstName);25             break;26     }27     return View(workers.ToList());28 }

The yellow part of the code above is what we added. In row 3, searchString transmits the string to the Controller for search. Line 2: Search if the string is not empty. The Where function in Linq is used for searching. It uses a Lambda expression to filter data that meets the conditions. This condition is the two Contains functions connected to "or" 9-10 rows. The Contains function indicates whether its string Contains its parameter string. The entire filter condition indicates that all records whose FisrtName or LastName contains the filter string are returned.

See below ~ \ Views \ Company \ Index. cshtml 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 above the table. It is a Form that contains an input box and a submit button. This Form submits the search string in the input box to the current Controller to complete the search operation. The input box is added with class and style for Bootstrap beautification.

View the page in a browser, enter B in the search box, and submit the page. The following page appears:

You can see that the search result is either FirstName or LastName, which contains all records of B (case-insensitive.

Paging

Data Query is free from paging. Here we use a plug-in named PagedList to implement this function.

Choose tool> program package management> package management console from the menu bar, as shown below.

A package Management Console window is displayed below the Visual Studio window. Enter Install-Package PagedList. Mvc. PagedList is automatically installed in the project. The window is as follows.

After the Paged List is installed, we start to modify the code, starting from 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     {11         private CompanyContext db = new CompanyContext();12         public ViewResult Index(string sortOrder, string searchString, string currentFilter, int? page)13         {14             ViewBag.CurrentSort = sortOrder;15             ViewBag.FirstNameSortParm = String.IsNullOrEmpty(sortOrder) ? "first_desc" : "";16             ViewBag.LastNameSortParm = sortOrder == "last" ? "last_desc" : "last";17             if(searchString != null)18             {19                 page = 1;20             }21             else22             {23                 searchString = currentFilter;24             }25             ViewBag.CurrentFilter = searchString;26 27             var workers = from w in db.Workers28                         select w;29             if (!string.IsNullOrEmpty(searchString))30             {31                 workers = workers.Where(w => w.FirstName.Contains(searchString)32                                         || w.LastName.Contains(searchString));33             }34             switch (sortOrder)35             {36                 case "first_desc":37                     workers = workers.OrderByDescending(w => w.FirstName);38                     break;39                 case "last_desc":40                     workers = workers.OrderByDescending(w => w.LastName);41                     break;42                 case "last":43                     workers = workers.OrderBy(w => w.LastName);44                     break;45                 default:46                     workers = workers.OrderBy(w => w.FirstName);47                     break;48             }49             int pageSize = 3;50             int pageNumber = (page ?? 1);51             return View(workers.ToPagedList(pageNumber,pageSize));52         }53     }54 }

Marked in yellow as the part to be modified. The first line references PagedList. The 12th-row currentFilter parameter is used to keep the search string intact during page turning. Rows 17th to 25 are used to search for a new string. The current page is automatically converted to the first page. Otherwise, the current page remains unchanged. Row 49-51 sets 3 data entries per page, sets the number of pages, and sends a View as a List. (Page ?? 1) it means that if the page is null, the value of page is assigned to 1. Otherwise, if the page is not null, the value is what it is. So we can set the hosts page to 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.BeginForm("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")10                </p>11            }12 <table class="table">13     <tr>14         <th>15             @Html.ActionLink("First Name", "Index", new { sortOrder = ViewBag.FirstNameSortParm })16         </th>17         <th>18             @Html.ActionLink("Last Name", "Index", new { sortOrder = ViewBag.LastNameSortParm })19         </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)28             </td>29             <td>30                 @Html.DisplayFor(modelItem => item.LastName)31             </td>32             <td>33                 @Html.DisplayFor(modelItem => item.Sex)34             </td>35             <td>36                 @Html.DisplayFor(modelItem => item.Rating)37             </td>38         </tr>39     }40 </table>41 <br/>42 Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount43 @Html.PagedListPager(Model, page => Url.Action("Index",44     new {page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter}))

Row 3 defines the model of the PagedList type. Row 3 references PagedList. Line 2: Introduce the css file related to PagedList. This file is automatically saved to the project when the plug-in is installed. The parameters of the BeginForm function of Line 1 change. The generated Form will use the Get method. The Get method will display the submitted parameters in the url, so that you can record the query parameters through the url, so that you can copy the url to others to display your query results. The first row is used to display the page number. Line 43-44 is used to generate buttons for each page.

When the page is displayed, click "2" at the bottom of the page to Go to page 2nd. The generated page is as follows:

The page button and page count at the bottom of the page are displayed, Which is elegant and elegant.

End

Well, it's almost midnight without knowing it. Come on!

If you like it, we recommend it!

Previous section: MVC5 + EF6 + Bootstrap3 (10) Data Query page

Author:Slark. NET

Source: http://www.cnblogs.com/slark/

The copyright of this article is shared by the author and the blog Park. You are welcome to repost this article. However, you must retain this statement without the author's consent and provide a clear link to the original article on the article page. Otherwise, you will be held legally liable. If you have any questions or suggestions, please give me some further information. Thank you very much.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.