ASP. Net MVC paging implementation method

Time:2022-1-1

In this article, we will learn how to implement paging in MVC pages. 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 pagedlist in MVC pages MVC package to realize paging function.

1) Install pagedlist Mvc

First, we need to install the paging component package. In Visual Studio 2010, click Project – manage nuget package to open the nuget package manager window. In this window, select the “online” tab, and then search pagedlist, as shown in the following figure. Click the “Install” button to install pagedlist The latest version of MVC (currently the latest version is 4.5.0).

Putting pagedlist After the MVC installation is completed, the pagedlist package is also installed. See the figure below.

Figure 1: pagedlist displayed in nuget package manager Mvc

2) Implement view entity object and controller with paging function

Put pagedlist After MVC is installed, the first thing is to add a view entity object to place some query attributes and query results. Add a viewbook in the models directory CS file, 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 searchindex method of the bookcontroller class so that books is returned as pagedlist (using the topagedlist () method). In order to use pagedlist, we also need to set the default sort. In order to use the pagedlist package, we first need to add using pagedlist at the top of the file; Code, and then modify controllers \ bookcontroller The CS file is the code shown in bold below.

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 options
    var orderbyLst = new Dictionary<string, string>
  {
   {"price from low to high", "price_lowest"},
   From "price" to "high" {
  };

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

   //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 above code has been launched several times. The first change is to add an int? Page parameter, which is an nullable integer and represents 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 classification is also saved in the view entity object, so we addedvbook.Category = Category;This line of code.

Codebooks = books.OrderBy(p => p.Name);It is used to sort the product list by default because pagedlist requires that the list must be a sequential table.

Next, we use the code const int pageitems = 5; To specify the amount of data displayed per 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 the product information, and the current page and the number of items displayed on each page are passed 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; Save the value of the sortby parameter to the sortby property of the view entity object so that when we move from one page to another, the sorting of products remains unchanged.

3) Query page with paging function

After modifying the code for paging in the view entity object and controller, now we need to update the view file \ views \ products \ searchindex Cshtml to display 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, an indication of the total number of books, and 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" />
<h2>Book query</h2>
  @using (Html.BeginForm("SearchIndex","book",FormMethod.Get)){ 
   <p>Book type: @ HTML DropDownList("category", "All") 
   Book Name: @ HTML TextBox("SearchString") 
    Sort: @ HTML Dropdownlist ("sortby", "do not sort")
   < input type = "submit" value = "query" / ></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>

<div>
  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 }))
 </div>

The paging link generation code is wrapped in the div tag. The first line of code uses?: The first line of the operator determines whether any page number is displayed. It displays “page 0 of 0” or “page X of Y”. X represents the current page number and Y represents the total number of pages.

The second line of code is from pagedlist Pagedlistpager helper for MVC namespace. The 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 classification, search criteria, sorting information and paging) to the helper method so that the link of each page contains a query string containing the current classification, search criteria, sorting information and paging information. This means that when moving from one page to another, the search criteria, selected classifications, and sorting rules are saved. If this is not done, the book list will be reset to show all book information.

After using the above code, sort the pagination interface by “price from low to high”, as shown in Figure 1 below.

Figure 1

We found that the digital part of the page is not good-looking. It turns out that we lack CSS and add the following code under 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 then sort the results according to “price from low to high”, as shown in Figure 2 below.

Figure 2: paging effect with search criteria, sorting and filtering by category

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support developpaer.