ASP. net mvc paging implementation method, asp. netmvc

Source: Internet
Author: User
Tags actionlink

ASP. net mvc paging implementation method, asp. netmvc

In this article, we will learn how to implement paging in the MVC page. The paging function is a very practical and commonly used function. When there is too much data, pagination is required. In this article, we will learn how to use the PagedList. MVC package on the Mvc page to implement the paging function.

1) install PagedList. Mvc

First, install the paging package. In Visual Studio 2010, click Project> Manage NuGet package to open the NuGet Package Manager form. In this form, select the "online" tab and search for pagedlist, as shown in. Click "Install" to install the latest version of PagedList. Mvc (the latest version is 4.5.0 ).

After installing PagedList. Mvc, The PagedList package is also installed. For example.

Figure 1: PagedList. Mvc shown in the NuGet Package Manager

2) Implement view object and controller with paging Function

After installing PagedList. Mvc, add a view object to store some query attributes and query results. Add a ViewBook. cs file under the Models directory. The Code is as follows:

using System;using System.Collections.Generic;using System.Linq;using System.Web;using PagedList; namespace MvcApplication1.Models{ public class ViewBook {   public IPagedList<Book> Books { get; set; }   public string Search { get; set; }     public string Category { get; set; }   public string SortBy { get; set; }   }}

Now we need to modify the SearchIndex method of the BookController class so that Books can be returned as a PagedList (using the ToPagedList () method ). To use PagedList, we also need to set the default sorting. To use the PagedList package, we first need to add the using PagedList at the top of the file; code, and then modify the following code in bold for the Controllers \ BookController. cs file.

Public ActionResult SearchIndex (string Category, string searchString, string sortBy, int? Page) {var cateLst = new List <string> (); var cateQry = from d in db. books orderby d. category select d. category; cateLst. addRange (cateQry. distinct (); ViewBag. category = new SelectList (cateLst); // sorting option var orderbyLst = new Dictionary <string, string >{{ "price from low to high", "price_lowest "}, {"price from high to low", "price_highest" }}; ViewBag. sortBy = new SelectList (orderbyLst, "Value", "Key"); // [2017-2-14 end] var B Ooks = from m in db. Books select m; if (! String. isNullOrEmpty (searchString) {books = books. where (s => s. name. contains (searchString);} // sort the results switch (sortBy) {case "price_lowest": books = books. orderBy (p => p. price); break; case "price_highest": books = books. orderByDescending (p => p. price); break; default: books = books. orderBy (p => p. name); break;} // pagination const int pageItems = 5; int currentPage = (page ?? 1); IPagedList <Book> pageBooks = books. toPagedList (currentPage, pageItems); // [2017-2-14] ViewBook vbook = new ViewBook (); vbook. books = pageBooks; vbook. category = Category; vbook. sortBy = sortBy; vbook. search = searchString; if (string. isNullOrEmpty (Category) vbook. books = pageBooks; else {vbook. books = pageBooks. where (x => x. category = Category ). toPagedList (currentPage, pageItems);} return View (vbook );}

The code above has been launched for the following times. The first change is to add an int? Page parameter, which is an empty integer that indicates the current page number selected by the user on the book query page. When you load the book query page for the first time, you have not selected any page number. Therefore, this parameter can be null.

We must ensure that the current category is also saved in the view object. Therefore, we have addedVbook. Category = Category;This line of code.

Code books = books. OrderBy (p => p. Name); used to sort the product list by default, because PagedList requires that the list be an ordered list.

Then, we use the code const int pageItems = 5; to specify the number of data displayed on each page. Then, we declare an integer variable int currentPage = (page ?? 1); To save the current page number. The value of this variable is the value of the page parameter, or 1 (when the page variable is null ).

We use the code vbook. books = books. toPagedList (currentPage, PageItems); The ToPagedList method is called for product information, and the data transmission of entries displayed on the current page and each page is handed to the ToPagedList method, then, the return value of this method is assigned to the Books attribute of the view object.

We use the code viewBook. SortBy = sortBy; To save the value of the sortBy parameter to the SortBy attribute of the view object, so that when we move from one page to another, the product order remains unchanged.

3) query page with paging Function

After modifying the code that implements the paging function in the view object and controller, We need to update the View File \ Views \ Products \ SearchIndex. cshtml: displays a page control in this view file so that users can move between pages. We also added instructions on how many data entries are there. To complete these functions, we have added a using statement to the file, showing the total number of books and displaying a paging control at the bottom of the page. The specific code is shown below:

@ Model MvcApplication1.Models. viewBook @ using PagedList. mvc @ {ViewBag. title = "book query ";} <link href = "/Content/PagedList.css" rel = "external nofollow" rel = "external nofollow" rel = "stylesheet" type = "text/css"/> 

Code generated by pagination links is enclosed in the div tag. The first line of code is used? : The first line of code of the operator determines whether any Page number is displayed. It displays "Page 0 of 0" or "Page x of y", x indicates the current Page number, and y indicates the total Page number.

The second line of code uses the PagedListPager helper from the PagedList. Mvc namespace. The Helper receives a product list parameter and generates a hyperlink for each page. Url. Action is used to generate a target that contains the parameter hyperlink of the current page. An anonymous type (containing the current category, search criteria, sorting information, and pagination) is passed to the helper method so that each page Link contains a query string, the query string contains the current category, search criteria, sorting information, and paging information. This means that when you move from one page to another, the search criteria, selected categories, and sorting rules are saved. If this is not done, the book list will be reset to display all the book information.

After using the above Code, sort the page by "price from low to high", such as 1.

Figure 1

We found that the numeric part of the page is not very nice. We used to reference CSS and add the following code below the title of the query page. The blue font in the above Code.

<Link href = "/Content/PagedList.css" rel = "external nofollow" rel = "external nofollow" rel = "stylesheet" type = "text/css"/>

Click the "query" button again and sort the results by "price from low to high". The result is as follows: 2.

Figure 2: Page effects with search criteria, sorting, and filtering by category

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.