ASP. MVC5 Pagedlist Pagination Example

Source: Internet
Author: User
Tags connectionstrings

ASP. NET MVC is a lightweight web development solution currently in ASP. In the ASP. NET MVC Overview of this translation, the difference between ASP. NET MVC and Web forms and their respective scenarios are described in detail. Since ASP. NET MVC is especially suitable for Web site development (Web Forms is more suitable for business system development), it is now the first framework for many web developers.

Here is a typical example (table pagination) to familiarize yourself with the development of ASP. Development environment: Windows 8.1 Enterprise Edition +vs2013 Ultimate +sql Server 2014.

Start by using VS2013 's wizard to create an ASP. NET MVC5 application.

This application can be run directly, provide some default features (registration, login) and their own implementation of the sample code, basically the developer reference to the code can be easily developed. Here by the way, VS2013 is very human, for developers to consider a lot.

First, modify the database configuration

Since this is an ASP. NET MVC application created by default, we'd better modify the database configuration to make it easier for us to develop. Open the Web. config file under the project root directory (note that it is not a Web. config under ~/views/).

Configure the DefaultConnection to:

<connectionStrings> <add name= "defaultconnection" connectionstring= "Uid=sa;pwd=123456;data source=         192.168.0.4; database=| Datadirectory|\studentdb.mdf;initial catalog=studentdb;integrated security=true "ProviderName=" System.Data.SqlCli Ent "/> </connectionStrings>

Since we are going to develop a paging demo, incidentally, under the appsettings configuration node, add:

<!--paging Condition: The number of records displayed per page-<add key= "PageSize" value= "8"/>

Second, create model

In general, we develop MVC applications, all starting from model. We create a new student model class under the project's Models folder.

namespace mvc5pagedemo.models{    public  enum sex    {        female, male     }    public class Student    {         public int ID { get; set; }         public string Name { get; set; }         public int Age { get; set; }         public Sex Sex { get; set; }         public double Score { get; set; }     }} 

Third, create data operation class

We'll start with a new Dal directory at the root of the project. Then, under the Dal directory, create a new Studentcontext class and let it inherit from DbContext. In this example, we use EF to implement database operations.

Due to the creation of the MVC5 app, EF6.0 has been introduced by default, and EF can be installed online without managing the NuGet package.

The Studentcontext code is as follows:

Namespace mvc5pagedemo.dal{public class Studentcontext:dbcontext {public Studentcontext (): Base ("Default    Connection ") {} public dbset<student> Students {get; set;} }}

We also need to use the pagedlist for paging, so we need to install it online. We can install it through the Package Manager console by entering commands.

650) this.width=650; "Src=" http://img.blog.csdn.net/20150224214543710?watermark/2/text/ ahr0cdovl2jsb2cuy3nkbi5uzxqvy2hpbmfjc2hhcnblcg==/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/dissolve/70/ Gravity/center "style=" Border:none;height:auto; "/>

This way, the DLLs we need are automatically added to the project.

Iv. Creating a Controller

MVC development called: Convention is greater than configuration. That is, when the controller is created, the class name is unified at the end of the controller, so we create a studentcontroller.

namespace mvc5pagedemo.controllers{    public class studentcontroller  :  controller    {        //Database Context Operations Object          private StudentContext db = new  Studentcontext ();         public viewresult index (int?  Page)         {             //Student List             var  Students = from s in db. students select s;            //first few pages             int pagenumber = page  ??  1;            //How many bars are displayed per page &nBsp;           int pagesize = int. Parse (configurationmanager.appsettings["PageSize"]);             //Sort by ID             students  = students. (x => x.id);             // Paging             IPagedList< by Topagedlist extension method Student> pagedlist = students. Topagedlist (pagenumber, pagesize);             //Pass the paginated list to view            return  View (pagedlist);         }    }}

As the above code requires the introduction of the Pagedlist namespace.

Using Pagedlist;

V. Create a view

Next to the index method in the Studentcontroller controller, right-add the view and select the appropriate option (you may not be able to add the view until you compile the project earlier).

650) this.width=650; "src="/e/u261/themes/default/images/spacer.gif "style=" Background:url ("/e/u261/lang/zh-cn/ Images/localimage.png ") no-repeat center;border:1px solid #ddd;" alt= "Spacer.gif"/>650 "this.width=650;" src= "http ://s3.51cto.com/wyfs02/m02/5b/15/wkiol1t_albzeunwaaftqwnbvw4664.jpg "title=" download. png "alt=" wKioL1T_ Albzeunwaaftqwnbvw4664.jpg "/>

Modify the newly created ~/student/index view file to:

@model  PagedList.IPagedList<MVC5PageDemo.Models.Student> @using  PagedList.Mvc;<link  href= "~/content/pagedlist.css"  rel= "stylesheet"  /><table class= "table" >     <tr>        <th>              name         </th>         <th>              Age         </th>         <th>             sex          </th>        <th >             score          </th>    </tr>     @foreach   (Var item in model)     {        <tr>             <td>                  @Html. Displayfor (Modelitem => item. Name)             </td>             <td>                  @Html. Displayfor (Modelitem => item. Age)             </td>             <td>                  @Html. Displayfor (Modelitem => item. SEX)             </td>             <td>                  @Html. Displayfor (Modelitem => item. Score)             </td>         </tr>    }</table> per page   @Model .pagesize  Records, total   @Model .pagecount  page, current   @Model .pagenumber  page @html.pagedlistpager (model, page  => url.action ("Index",  new { page }))

VI. Preparation of test data

Create a new initializer directory at the root of the project, then create a new Studentinitializer class in it and inherit from system.data.entity.dropcreatedatabasealways< Studentcontext>.

Namespace mvc5pagedemo.initializer{    public class studentinitializer  : System.Data.Entity.DropCreateDatabaseAlways<StudentContext>    {         protected override void seed (StudentContext  Context)         {             List<Student> students = new List<Student> ();             for  (int i = 1; i  < 40; i++)             {                 student student  = new student ();                 student.id = i;                 Student. name =  "Zhang"  + i;                 student. age = 10 + i;                 student. sex = i % 2 == 0 ? sex.female : sex.male;                 student. score = 60 + i;                 students. ADD (student);            }             context. Students.addrange (Students);             context.SaveChanges ();         }    }} 

Add the following configuration under the EntityFramework node of the Web. config:

<contexts> <context type= "Mvc5pagedemo.dal.studentcontext,mvc5pagedemo" > <databaseinitializer type = "Mvc5pagedemo.initializer.studentinitializer,mvc5pagedemo"/> </context> </contexts>

MVC5PageDemo.DAL.StudentContext is the namespace name + class name, and the mvc5pagedemo behind the comma is the name of the DLL file where the Studentcontext class resides. The configuration of the Databaseinitializer under the context node is similarly.


A development based on the ASP. NET MVC5 paging table is completed.

The final:

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M01/5B/15/wKioL1T_AkbAn5iWAAGETdP0VCo117.jpg "title=" Download (1). PNG "alt=" wkiol1t_akban5iwaagetdp0vco117.jpg "/>

ASP. MVC5 Pagedlist Pagination Example

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.