Paging and sorting, should be in software development, need to know will be the skills, for pagination, online many tutorials, of course, others are others, only their understanding, will, and absorption, and then use their own language, imparting out, this is the hard truth. Well, that's a lot of crap. Now let's get to the point:
Here, I intend to use the EF code-first Way paging control is to use PAGEDLIST.MVC, to do pagination, for sorting, the idea is that the load data out, the default is ascending sort, and then we click on the corresponding column headings, according to the field descending sort, check the data. If you have a clear idea, start doing it!
1. First create a blank MVC project, in the Model folder, create a new student entity
Student the code in the entity:
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Namespace Pagingandsortinginmvc.models
{public
class Student
{public
int ID {get; set;}
public string Name {get; set;}
public string Sex {get; set;}
public string Email {get; set;}
public int Age {get; set;}}}
2. After adding the EF reference, we create a folder map in the root directory and create a class inside the Studentmap
Code for the Studentmap class:
Using Pagingandsortinginmvc.models;
Using System;
Using System.Collections.Generic;
Using System.ComponentModel.DataAnnotations.Schema;
Using System.Data.Entity.ModelConfiguration;
Using System.Linq;
Using System.Web;
Namespace Pagingandsortinginmvc.map
{public
class studentmap:entitytypeconfiguration<student>
{public
studentmap ()
{
//Configure primary key this
. Haskey (S => s.id);
Set the ID column to the self-add column this
. Property (S => s.id). Hasdatabasegeneratedoption (databasegeneratedoption.identity);
Configuration column this
. Property (S => s.name). Hasmaxlength (50). IsRequired ();
This. Property (S => s.sex). Hasmaxlength (2). IsRequired ();
This. Property (S => s.age). IsRequired ();
This. Property (S => s.email). Hasmaxlength (100). IsRequired ();}}
3. In the root directory, and then create a new folder DBHelper, create a new class inside Studentdbcontext
Code for the Studentdbcontext class:
Using Pagingandsortinginmvc.map;
Using System;
Using System.Collections.Generic;
Using System.Data.Entity;
Using System.Linq;
Using System.Web;
Namespace Pagingandsortinginmvc.dbhelper
{public
class Studentdbcontext:dbcontext
{
public Studentdbcontext ()
: Base ("name=dbconnectionstring")
{
}
protected override void Onmodelcreating (Dbmodelbuilder modelbuilder)
{
//Because there is only one entity, it's not so complicated, it doesn't have to be reflected. Add the configuration
modelBuilder.Configurations.Add (New Studentmap ()) directly to a single entity;
Base. Onmodelcreating (ModelBuilder);}}
Then add the following in the configuration file:
<connectionStrings>
<add name= "dbconnectionstring" connectionstring= "server=.;D Atabase=mystudentdb; Uid=sa; Pwd=password_1 "providername=" System.Data.SqlClient "/>
</connectionStrings>
The exact location is here:
4. OK, now that the entity and database configuration are all written, now we use the database migration technology "migrations" to automatically generate the database , first open the package management console.
Add a line of statements: Enable-migrations, and then press ENTER:
This time, in our program generated a folder migrations, which has a class configuration:
To modify the code in the configuration class: Set the automaticmigrationsenabled to True, and add a code that allows no data loss during migration:
automaticmigrationdatalossallowed = false;
Then enter the following in the package management console:
update-database-verbose
Note: "There are spaces between-verbose and database," and the reason you enter-verbose is that you can see the resulting SQL statement in the console:
pm> update-database-verbose Using StartUp project ' Pagingandsortinginmvc '.
Using NuGet project ' Pagingandsortinginmvc '.
Specify the "-verbose ' flag to view" SQL statements being to the target database.
Target database is: ' Mystudentdb ' (DataSource:., Provider:System.Data.SqlClient, origin:configuration).
No pending explicit migrations.
Applying automatic migration:201607180249098_automaticmigration. CREATE TABLE [dbo]. [Students] ([ID] [int] NOT NULL IDENTITY, [Name] [nvarchar] (a) not NULL, [Sex] [nvarchar] (2) not NULL, [Email] [nvarchar] (100) Not NULL, [age] [int] NOT NULL, CONSTRAINT [pk_dbo. Students] PRIMARY KEY ([ID]) CREATE TABLE [dbo]. [__migrationhistory] ([Migrationid] [nvarchar] (not NULL, [Contextkey] [nvarchar] (+) not NULL, [Model] [varbinary] (max) is not null, [P Roductversion] [nvarchar] (a) not NULL, CONSTRAINT [pk_dbo.__migrationhistory] PRIMARY KEY ([Migrationid], [Contextkey] ) INSERT [dbo]. [__migrationhistory] ([Migrationid], [conteXtkey], [Model], [productversion]) VALUES (n ' 201607180249098_automaticmigration ', n ' Pagingandsortinginmvc. Migrations.configuration ', 0x1f8b0800000000000400cd57db6edb38107d5fa0ff20f03935ed040b7403b9856327bbc6d64950a579a7a5b1422c456a492ab0bfad0ffb49fb0b3bd 4dd926f31da451120b0a8993333673817fdfbed1fffd33a11de2b68c3951c93d160483c90a18ab88cc724b3abf71fc8a78fef7ef16fa364ed3d577257 4e0e35a51993176bd36b4a4df80209338384875a19b5b283502594458a5e0e87bfd1d188024210c4f23cff4b262d4f207fc0c7a99221a4366362a1221 0a63cc737418eeaddb3044cca4218934716a36f1319054a5bfc35978be7e96076f307881434f1268233f42a00b1221e93525966d1e7ebaf0602ab958c 83140f9878daa480722b260c94b15c37e2a78635bc7461d146b1820a336355f246c0d155c913edaa9fc536a97944266f9171bb7151e76c2243368b405 Ae2756d5d4f857672fbb82e723428f52fbc9d5217f565c13be5fe2ebc69266ca6612c21b39a0954cc9682877fc2e649fd05722c3321da2ea3d3f86eeb 008f1eb5c23cdbcd17589581cc67c4a3db7ab4ab58abb5748a18e7d25e5d12ef1e8db3a580fa46b4f808acd2f03b48d0cc42f4c8ac058d099dbbf091d 39ef58e2df7bfb28657101922de82ad3f838cedcb98fc8aa574c7d7105507a5035f25c73a441dab33d8e1e061a301ac0fd8bcfc11266f13c6c501a3a3e10f897412c3b15cb601 7cda5442bf3eb01359c631d3db4532bb712f60bdab5ab0b1940563ca08b6dd2d8003b0db9086788d2345bf1ad425b9cbe1dab5a63bd2a23d566d94eee 9a3fe82a52966a3d557cb132f289aeaf47df0f60e93141834343b1a4ded6d6d098b88c5d0798ba6d1d33bae8d9d31cb96cca56b1a253db15e22f6905c 99eb70dded220df59582fb5d281d9e3075923a900da9771867821279c8507bd674dc9e663ee898607a47979a2a9125725fa73ba45df49db67e71723a4 2de44da00f9c1e9fa654768239447a763e4e5dd46c80ffafa3eedd0df4d39ede5bc3333ba77e8500d76456aeb752d766ace2feffff105a757108508f1 9098571ee5c5b0311692811318047f8ba9e079d7a804164cf215185b8c5582f5faa1b317fd3c3b0a352612a72d2afffb6ac01da94787ff1bc7557b1b9 0af4c872f4cf7f681f387fd4ec86333f1c82cdf89994ff3f34775ceed771cd4fd3172d2143e34848bba1b9368a9d0ebc2cf66789f39a2fb6dc0a7edaf 217f0686c70d84fb369210bafa6a402b99b95ca98a620caded5125d2c9c0022c8b90a1094eb6150b2dbe0ec1987c557b6622cb53bf84682e1f329b667 6620c244bb1b5e3faf4b0fd7c0fd9f6d97f48dd93f91e21a09b1c43800779937111d57edfedb8427b20dc65294b1abdc25515e1e24d8d74afe48940257d334841ba7bf104492a10cc3cc880bd
c239bee13af91962166eaa6ebe1fe47822b669f7679cc59a25a6c468f4dd173e759ff81fff0366e046f514100000, N ' 6.1.3-40302 ')
Running Seed method.
Pm>
When we open the database, we see the database and the table we want to build:
Now that you want to split the page, start introducing the paging control, introducing the PAGEDLIST.MVC
5. Create a new student controller for a blank template.
Inside the controller is our main logical code:
Using Pagingandsortinginmvc.dbhelper;
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using SYSTEM.WEB.MVC;
Using Pagedlist;
Using Pagingandsortinginmvc.models; Namespace Pagingandsortinginmvc.controllers {public class Studentcontroller:controller {private Studentdbcontext db
=null;
Public Studentcontroller () {db = new Studentdbcontext (); ///<summary>///Home "query paging Data"///</summary>///<param name= "SortBy" > According to what sort </param>///& Lt;param name= "Currentsort" > Current sort field </param>///<param name= "page" > Current page </param>///<returns
></returns> public ActionResult Index (string sortby,string currentsort,int? page) {int pageIndex = 1;
int pageSize = 5; To determine whether the page has a value, some words to the value, not to assign a value of 1 PageIndex = page. HasValue?
Convert.ToInt32 (page): 1;
Viewbag.currentsort = SortBy;
This must be, otherwise the first is empty, the error, you can not cycle. SortBy = string. IsNullOrEmpty (sortby)? "Name": sortby; If SortBy is empty, it is set to name, and the following settings areThe default is sorted by name ipagedlist<student> lststudent = null; Switch (sortby) {case ' Name '://If sortby==currentsort, arrange the corresponding fields in descending order, and pagination.
otherwise ascending. if (Sortby.equals (Currentsort)) {lststudent = db.
Set<student> ().
OrderByDescending (S => s.name). Topagedlist (PageIndex, pageSize); According to the advice of an enthusiastic blogger, add this sentence, click on the corresponding column, ascending descending loop.
Viewbag.currentsort = null; else {lststudent = db.
Set<student> ().
By (S => s.name).
Topagedlist (PageIndex, pageSize);
} break; Case "Sex"://If sortby==currentsort, follow the corresponding field in descending order, and pagination.
otherwise ascending. if (Sortby.equals (Currentsort)) {lststudent = db.
Set<student> ().
OrderByDescending (S => s.sex). Topagedlist (PageIndex, pageSize); According to the advice of an enthusiastic blogger, add this sentence, click on the corresponding column, ascending descending loop.
Viewbag.currentsort = null; else {lststudent = db.
Set<student> ().
By (S => s.sex).
Topagedlist (PageIndex, pageSize);
} break; Case "Email"://If Sortby==currEntsort, the corresponding fields are sorted in descending order and paginated.
otherwise ascending. if (Sortby.equals (Currentsort)) {lststudent = db.
Set<student> ().
OrderByDescending (S => s.email). Topagedlist (PageIndex, pageSize); According to the advice of an enthusiastic blogger, add this sentence, click on the corresponding column, ascending descending loop.
Viewbag.currentsort = null; else {lststudent = db.
Set<student> ().
By (S => s.email).
Topagedlist (PageIndex, pageSize);
} break; Case ' age '://If sortby==currentsort, arrange the corresponding fields in descending order, and pagination.
otherwise ascending. if (Sortby.equals (Currentsort)) {lststudent = db.
Set<student> ().
OrderByDescending (S => s.age). Topagedlist (PageIndex, pageSize); According to the advice of an enthusiastic blogger, add this sentence, click on the corresponding column, ascending descending loop.
Viewbag.currentsort = null; else {lststudent = db.
Set<student> ().
By (S => s.age).
Topagedlist (PageIndex, pageSize);
} break; Default://If sortby==currentsort, arrange the corresponding fields in descending order, and pagination.
otherwise ascending. if (Sortby.equals (Currentsort)) {lststudent = db.
Set<student> (). OrdeRbydescending (S => s.name). Topagedlist (PageIndex, pageSize); According to the advice of an enthusiastic blogger, add this sentence, click on the corresponding column, ascending descending loop.
Viewbag.currentsort = null; else {lststudent = db.
Set<student> ().
By (S => s.name).
Topagedlist (PageIndex, pageSize);
} break;
Return View (lststudent);
Public ActionResult Addstudent () {return View (); [HttpPost] [Validateantiforgerytoken] public actionresult addstudent (Student model) {db. Set<student> ().
ADD (model); Db.
SaveChanges ();
Return redirecttoaction ("Index");
}
}
}
To create a corresponding index view and addstudent view:
Index View:
@using pagedlist.mvc;@*//to introduce paging components *@ @model pagedlist.ipagedlist<pagingandsortinginmvc.models.student> @{
Viewbag.title = "Index";
} <style> Table {width:100%;
Table TR td {BORDER:2PX solid black;
Text-align:center;
Word-wrap:break-word;
Table Tr:hover {background-color: #000;
Color: #fff;
Table TR th {border:2px solid black;
Text-align:center;
Background-color: #fff;
Color: #000; } </style>
Addstudent view:
@model PagingAndSortingInMVC.Models.Student @{viewbag.title = "Addstudent";}
Then modify the layout page:
Modify the default route:
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using SYSTEM.WEB.MVC;
Using System.Web.Routing;
Namespace Pagingandsortinginmvc
{public
class Routeconfig
{public
static void RegisterRoutes ( RouteCollection routes)
{
routes. Ignoreroute ("{resource}.axd/{*pathinfo}");
Routes. Maproute (
name: "Default",
URL: "{controller}/{action}/{id}",
defaults:new {controller = "Student", Action = "Index", id = urlparameter.optional}
);}}
To run the project:
No data at first, we add a few test data:
Let's verify the results:
See, click on the corresponding column headings can be sorted. Pagination is also implemented. Of course the pagination style can be changed by changing this option:
@Html. Pagedlistpager (Model, page => url.action ("Index", new {page}), Pagedlistrenderoptions.classic)
Here, I have modified
@Html. Pagedlistpager (Model, page => url.action ("Index", new {page}), Pagedlistrenderoptions.twitterbootstrappager )
The effect of pagination controls is this.
Well, here's the end of the article.
Summary: Paging and sorting is a very important function that requires mastery.
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.