Home  >  Article  >  Backend Development  >  Introduction to the implementation method of paging using ASP.NET MVC

Introduction to the implementation method of paging using ASP.NET MVC

高洛峰
高洛峰Original
2017-03-19 10:36:331521browse

This article mainly introduces the implementation method of ASP.NET MVCpagination in detail. It has certain reference value for those who are interested. You can refer to

In this article, we will learn how to implement paging in MVC pages. The paging function is a very practical and commonly used function. When there is too much data, paging must be used. In today's article, we learn how to use the PagedList.Mvc package in an MVC page to implement paging functionality.

1) Install PagedList.Mvc

First, we need to install the paging component package, click [Project]-[Manage NuGet Package] in Visual Studio 2010, Open the NuGet package manager form, in the form, select the "Online" tab, and then search for pagedlist, as shown in the image below. Click the "Install" button to install the latest version of PagedList.Mvc (the latest version is currently 4.5.0).

使用ASP.NET MVC分页的实现方法介绍

After the installation of PagedList.Mvc is completed, the PagedList package is also installed. As shown below.

使用ASP.NET MVC分页的实现方法介绍

Figure 1: PagedList.Mvc displayed in the NuGet package manager

2) Implement the view entity object and controller with paging function

After installing PagedList.Mvc, the first thing is to add a view entity object to place some query attributes and query results. Create a new ViewBook.cs file in 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; }  
 }
}


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


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

   //排序选项
    var orderbyLst = new Dictionary<string, string>
  {
   { "价格从低到高", "price_lowest" },
   { "价格从高到低", "price_highest" }
  };

    ViewBag.sortBy = new SelectList(orderbyLst, "Value", "Key");
   // [2017-2-14 end]
   var books = 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;
   } 

   //分页
   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 above code has been launched several times. The first change is to add an int? page parameter, which is an A nullable integer, representing the current page number selected by the user in the book query page. When the book query page is loaded for the first time, the user has not selected any page number, so this parameter can be null.

We must ensure that the current category is also saved in the view entity object, so we add the vbook.Category = Category; line of code.

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

Next, we use the code const int pageItems = 5; to specify the number of data displayed on each page. Then, we declared 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);, call the ToPagedList method on the product information, and pass the current page and the number of items displayed on each page to the ToPagedList method, and then The return value of this method is assigned to the Books property of the view entity object.

We use the code viewBook.SortBy = sortBy; to save the value of the sortBy parameter to the SortBy property of the view entity object so that the sorting of the products remains unchanged when we move from one page to another.

3) Query page with paging function

After modifying the code that implements paging function in the view entity object and controller, now we need to update the view file\Views\Products\ SearchIndex.cshtml, displays a paging control in this view file so that users can move between pages. We also added an indication of how many pieces of data there are. In order to complete these functions, we added a using statement to the file, an indication of the total number of books and a paging control displayed at the bottom of the page. The specific code is as follows:

##

@model MvcApplication1.Models.ViewBook
 @using PagedList.Mvc

@{

 ViewBag.Title = "书籍查询";
}
 <link href="/Content/PagedList.css" rel="external nofollow" rel="external nofollow" rel="stylesheet" type="text/css" />
<h2>书籍查询</h2>
  @using (Html.BeginForm("SearchIndex","book",FormMethod.Get)){ 
   <p>书籍种类: @Html.DropDownList("category", "All") 
   书籍名称: @Html.TextBox("SearchString") 
    排序: @Html.DropDownList("sortBy", "不排序")
   <input type="submit" value="查询" /> </p>
  }

<table>
 <tr>
  <th>
   @Html.DisplayNameFor(model => model.Books.First().Category)
  </th>
  <th>
   @Html.DisplayNameFor(model => model.Books.First().Name)

  </th>
  <th>
   @Html.DisplayNameFor(model => model.Books.First().Numberofcopies)

  </th>
  <th>
   @Html.DisplayNameFor(model => model.Books.First().AuthorID)

  </th>
  <th>
   @Html.DisplayNameFor(model => model.Books.First().Price)

  </th>
  <th>
   @Html.DisplayNameFor(model => model.Books.First().PublishDate)

  </th>
  <th></th>

 </tr>
@foreach (var item in Model.Books) {

 <tr>
  <td>
   @Html.DisplayFor(modelItem => item.Category)

  </td>
  <td>
   @Html.DisplayFor(modelItem => item.Name)

  </td>
  <td>
   @Html.DisplayFor(modelItem => item.Numberofcopies)

  </td>
  <td>
   @Html.DisplayFor(modelItem => item.AuthorID)

  </td>
  <td>
   @Html.DisplayFor(modelItem => item.Price)

  </td>
  <td>
   @Html.DisplayFor(modelItem => item.PublishDate)

  </td>
  <td>
   @Html.ActionLink("Edit", "Edit", new { id=item.BookID }) |

   @Html.ActionLink("Details", "Details", new { id=item.BookID }) |

   @Html.ActionLink("Delete", "Delete", new { id=item.BookID })

  </td>
 </tr>
}
</table>

<p>
  Page @(Model.Books.PageCount < Model.Books.PageNumber ? 0 : Model.Books.PageNumber) of @Model.Books.PageCount

  @Html.PagedListPager(Model.Books, page => Url.Action("SearchIndex", new { category = Model.Category, 
search = Model.Search, sortBy = Model.SortBy, page }))
 </p>

The paging link generation code is wrapped in the p tag. The first line of code uses the ?: operator to determine whether there is any page number to display. It displays "Page 0 of 0" or "Page x of y", x represents the current page number, y Indicates the total number of pages.

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

After using the above code, the paging interface is sorted by "price from low to high", as shown in Figure 1 below.

使用ASP.NET MVC分页的实现方法介绍

Figure 1

We found that the number part of the paging is not good-looking. It turns out that we lacked the CSS reference. Add the following code below the title of the query page . The blue font in the above code.

ee504bee5c2da6a70d70d73e3ad119c1

Click the "Query" button again, and then sort the results according to "price from low to high". The effect is as shown in Figure 2.

使用ASP.NET MVC分页的实现方法介绍

Figure 2: Paging effect with search conditions, sorting and filtering by category


The above is the detailed content of Introduction to the implementation method of paging using ASP.NET MVC. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn