Introduction to the implementation method of using ASP.

Source: Internet
Author: User
Tags actionlink visual studio 2010
This article mainly for you to introduce the ASP. NET MVC page implementation method, with a certain reference value, interested in small partners can refer to





In this article, we'll learn how to implement pagination in an MVC page. Paging is a very useful and common function, when the amount of data is too high, it is necessary to use paging. In today's article, we learn 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 Packages" in Visual Studio 2010, open the NuGet Package Manager form, select the "Online" tab in the form, and then search for Pagedlist, as shown in. Click the "Install" button to install the latest version of PAGEDLIST.MVC (currently the latest version is 4.5.0).






After the installation of the PAGEDLIST.MVC, the Pagedlist package was installed. Such as.






Figure 1:nuget the PAGEDLIST.MVC shown in Package Manager



2) Implement view entity object and controller with paging function



Once the PAGEDLIST.MVC is installed, the first thing to do is to add a view entity object to place some query properties and query results. Add a new ViewBook.cs file under the models directory, as shown in the following code:





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 returns as Pagedlist (using the Topagedlist () method). In order to use pagedlist, we also need to set the default ordering. In order to use the Pagedlist package, we first need to add a using pagedlist at the top of the file, code, and then modify the Controllers\bookcontroller.cs file to display the code in the following 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);

   // sorting options
    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 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 the following several times, the first change is to add an int? Page parameter, which is a nullable integer that 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 numbers, so this parameter can be null.



We have to make sure that the current classification is also saved in the View entity object, so we added Vbook. Category = category; This line of code.



Code books = books. (p = p.name); Used to sort the list of products by default, because the Pagedlist requirement list must be a sequential table.



Next, we use the code const INT PAGEITEMS = 5 to specify the number of data to display per page. We then declared an integer variable int currentpage = (page?? 1); To save the current page number, the value of the variable is the value of the page parameter, or 1 (when the page variable is null).



We use code Vbook. Books = Books. Topagedlist (CurrentPage, Pageitems), called the Topagedlist method on the product information, and passed the current page and the number of entries displayed on each page to the Topagedlist method, The return value of the method is then assigned to the Books property of the View entity object.



We use 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 page to page, the product sort remains the same.



3) query page with paging function



After modifying the code that implements paging in view entity objects and controllers, we now need to update the view file \views\products\searchindex.cshtml to display a paging control in this view file so that the user can move between pages. We have also added instructions for how many data are available. To complete these functions, we have added a using statement to the file, an indication of the total number of books, and a paging control at the bottom of the page, as shown in the following code:


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

@ {

 ViewBag.Title = "Book Search";
}
 <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>

<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 pagination link generation code is wrapped in p tags. The first line of code uses the?: Operator to determine whether any page numbers are displayed. It displays "Page 0 of 0" or "Page x of y", where x is the current page number and y is the total number of pages.

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 hyperlink target with the current page parameters. We pass an anonymous type (containing the current classification, search conditions, sorting information, and pagination) to the helper method so that the link for each page contains a query string that contains the current classification, search conditions , Sorting information, and paging information. This means that when moving from one page to another, search criteria, selected classifications, and sorting rules are saved. If this is not done, the book list will be reset to display all book information.

After using the above code, sort the pagination interface by "price from low to high", such as 1.

We found that the digital part of the page is not good-looking. It turned out that we lacked a reference to CSS. Add the following code below the title of the query page. 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", the effect is as 2.

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.