ASP. net mvc paging and sorting functions, asp. netmvc

Source: Internet
Author: User
Tags sorted by name actionlink

ASP. net mvc paging and sorting functions, asp. netmvc

Paging and sorting should be essential skills in software development. For paging and many online tutorials, of course, after all, others are others'. They only have their own understanding, this is the truth. Okay, it's a lot of nonsense. Now let's go to the question:

Here, I plan to use PagedList for the page control in EF Code-First mode. MVC is used for paging. for sorting, the idea is that after the data is loaded, it is sorted in ascending order by default. Then we click the corresponding column title, query data in descending order of the field. If you have a clear idea, let's get started!

1. Create a blank MVC project and create a Student object in the Model folder.

Code in Student object:

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 EF reference is added, create a folder Map under the root directory and create a class StudentMap. 

Code of the StudentMap class:

Using PagingAndSortingInMVC. models; 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 the primary key this. hasKey (s => s. ID); // set the ID column as an auto-incrementing column this. property (s => s. ID ). hasDatabaseGeneratedOption (DatabaseGeneratedOption. identity); // configure the 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. Create a new folder DBHelper under the root directory and create a class StudentDBContext

Code of the StudentDBContext class:

Using PagingAndSortingInMVC. map; 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 that complicated, so we don't need reflection. Directly Add the configuration modelBuilder. Configurations. Add (new StudentMap (); base. OnModelCreating (modelBuilder) ;}} of a single object );}}}

Then add the following in the configuration file:

<connectionStrings><add name="DbConnectionString" connectionString="Server=.;Database=MyStudentDB;UID=sa;PWD=Password_1" providerName="System.Data.SqlClient"/></connectionStrings> 

The specific location is here:

4. Now we have all the physical and database configurations.Use Database Migration Technology [Migrations] to automatically generate DatabasesFirst, open the package management console.
Add the following statement: Enable-Migrations and press Enter:

At this time, a folder Migrations is generated in our program, which contains a class Configuration:

Modify the code in the Configuration class: Set AutomaticMigrationsEnabled to true, and add a code to prevent data loss during migration:
AutomaticMigrationDataLossAllowed = false;

In the package management console, enter:
 Update-Database-Verbose

Note:[-There is a space between Verbose and Database]. The reason for entering-Verbose is that you can see the generated SQL statement on the console:

PM> Update-Database -VerboseUsing StartUp project 'PagingAndSortingInMVC'.Using NuGet project 'PagingAndSortingInMVC'.Specify the '-Verbose' flag to view the SQL statements being applied 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](50) 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](150) NOT NULL, [ContextKey] [nvarchar](300) NOT NULL, [Model] [varbinary](max) NOT NULL, [ProductVersion] [nvarchar](32) 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', 0x1F8B0800000000000400CD57DB6EDB38107D5FA0FF20F03935ED040B7403B9856327BBC6D64950A579A7A5B1422C456A492AB0BFAD0FFB49FB0B3BD4DD926F31DA451120B0A8993333673817FDFBED1FFFD33A11DE2B68C3951C93D160483C90A18AB88CC724B3ABF71FC8A78FEF7EF16FA364ED3D5772574E0E35A51993176BD36B4A4DF80209338384875A19B5B283502594458A5E0E87BFD1D188024210C4F23CFF4B262D4F207FC0C7A99221A4366362A12210A63CC737418EEADDB3044CCA4218934716A36F1319054A5BFC35978BE7E96076F307881434F1268233F42A00B1221E93525966D1E7EBAF0602AB958C83140F9878DAA480722B260C94B15C37E2A78635BC7461D146B1820A336355F246C0D155C913EDAA9FC536A97944266F9171BB7151E76C2243368B405AE2756D5D4F857672FBB82E723428F52FBC9D5217F565C13BE5FE2EBC69266CA6612C21B39A0954CC9682877FC2E649FD05722C3321DA2EA3D3F86EEB008F1EB5C23CDBCD17589581CC67C4A3DB7AB4AB58ABB5748A18E7D25E5D12EF1E8DB3A580FA46B4F808ACD2F03B48D0CC42F4C8AC058D099DBBF091D39EF58E2DF7BFB28657101922DE82AD3F838CEDCB98FC8AA574C7D7105507A5035F25C73A441DAB33D8E1E061A301AC0FD8BCFC11266F13C6C501A3A3E10F897412C3B15CB6017CDA5442BF3EB01359C631D3DB4532BB712F60BDAB5AB0B1940563CA08B6DD2D8003B0DB9086788D2345BF1AD425B9CBE1DAB5A63BD2A23D566D94EEE9A3FE82A52966A3D557CB132F289AEAF47DF0F60E93141834343B1A4DED6D6D098B88C5D0798BA6D1D33BAE8D9D31CB96CCA56B1A253DB15E22F6905C99EB70DDED220DF59582FB5D281D9E3075923A900DA9771867821279C8507BD674DC9E663EE898607A47979A2A9125725FA73BA45DF49DB67E71723A42DE44DA00F9C1E9FA654768239447A763E4E5DD46C80FFAFA3EEDD0DF4D39EDE5BC3333BA77E8500D76456AEB752D766ACE2FEFFFF105A757108508F19098571EE5C5B0311692811318047F8BA9E079D7A804164CF215185B8C5582F5FAA1B317FD3C3B0A352612A72D2AFFFB6AC01DA94787FF1BC7557B1B90AF4C872F4CF7F681F387FD4EC86333F1C82CDF89994FF3F34775CEED771CD4FD3172D2143E34848BBA1B9368A9D0EBC2CF66789F39A2FB6DC0A7EDAF217F0686C70D84FB369210BAFA6A402B99B95CA98A620CADED5125D2C9C0022C8B90A1094EB6150B2DBE0EC1987C557B6622CB53BF84682E1F329B6676620C244BB1B5E3FAF4B0FD7C0FD9F6D97F48DD93F91E21A09B1C43800779937111D57EDFEDB8427B20DC65294B1ABDC25515E1E24D8D74AFE48940257D334841BA7BF104492A10CC3CC880BDC239BEE13AF91962166EAA6EBE1FE47822B669F7679CC59A25A6C468F4DD173E759FF81FFF0366E046F514100000 , N'6.1.3-40302')Running Seed method.PM> 

Open the database and we can see that the database and table we want are generated:

Since paging is required, introduce the paging control and PagedList. MVC.

5. Create a new Student controller for the blank template.

The controller contains our main logic code:

Using PagingAndSortingInMVC. DBHelper; 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> // homepage [query the number of pages Data] /// </summary> /// <param name = "sortBy"> sort by </param> /// <param name = "currentSort"> current order 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; // determines whether a page has a value. If yes, the page is assigned a value. If no value exists, 1 pageIndex = page. HasValue is assigned? Convert. ToInt32 (page): 1; ViewBag. CurrentSort = sortBy; // This sentence is required. Otherwise, it is blank at the beginning. If an error is returned, it cannot be recycled. SortBy = string. IsNullOrEmpty (sortBy )? "Name": sortBy; // If sortBy is empty, it is set to Name. In the following settings, IPagedList is sorted by Name by default. <Student> lstStudent = null; switch (sortBy) {case "Name": // If sortBy = currentSort, the corresponding fields are sorted in descending order and displayed on pages. Otherwise, it is in ascending order. If (sortBy. equals (currentSort) {lstStudent = db. set <Student> (). orderByDescending (s => s. name ). toPagedList (pageIndex, pageSize); // Add this sentence according to the advice of an enthusiastic blogger, click the corresponding column, and sort the statements in ascending and descending order. ViewBag. currentSort = null;} else {lstStudent = db. set <Student> (). orderBy (s => s. name ). toPagedList (pageIndex, pageSize);} break; case "Sex": // If sortBy = currentSort, sort the fields in descending order and pagination. Otherwise, it is in ascending order. If (sortBy. equals (currentSort) {lstStudent = db. set <Student> (). orderByDescending (s => s. sex ). toPagedList (pageIndex, pageSize); // Add this sentence according to the advice of an enthusiastic blogger, click the corresponding column, and sort the statements in ascending and descending order. ViewBag. currentSort = null;} else {lstStudent = db. set <Student> (). orderBy (s => s. sex ). toPagedList (pageIndex, pageSize);} break; case "Email": // If sortBy = currentSort, sort the fields in descending order and pagination. Otherwise, it is in ascending order. If (sortBy. equals (currentSort) {lstStudent = db. set <Student> (). orderByDescending (s => s. email ). toPagedList (pageIndex, pageSize); // Add this sentence according to the advice of an enthusiastic blogger, click the corresponding column, and sort the statements in ascending and descending order. ViewBag. currentSort = null;} else {lstStudent = db. set <Student> (). orderBy (s => s. email ). toPagedList (pageIndex, pageSize);} break; case "Age": // If sortBy = currentSort, sort the fields in descending order and pagination. Otherwise, it is in ascending order. If (sortBy. equals (currentSort) {lstStudent = db. set <Student> (). orderByDescending (s => s. age ). toPagedList (pageIndex, pageSize); // Add this sentence according to the advice of an enthusiastic blogger, click the corresponding column, and sort the statements in ascending and descending order. ViewBag. currentSort = null;} else {lstStudent = db. set <Student> (). orderBy (s => s. age ). toPagedList (pageIndex, pageSize);} break; default: // If sortBy = currentSort, It is sorted in descending order according to the corresponding fields and displayed on pages. Otherwise, it is in ascending order. If (sortBy. equals (currentSort) {lstStudent = db. set <Student> (). orderByDescending (s => s. name ). toPagedList (pageIndex, pageSize); // Add this sentence according to the advice of an enthusiastic blogger, click the corresponding column, and sort the statements in ascending and descending order. ViewBag. currentSort = null;} else {lstStudent = db. set <Student> (). orderBy (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 ");}}}

Create the corresponding Index view and AddStudent View:

Index View:

@ Using PagedList. mvc; @ * // introduce the paging component * @ 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 ;}</styl E> 

AddStudent View:

@model PagingAndSortingInMVC.Models.Student@{ ViewBag.Title = "AddStudent";}

Next, modify the layout page:

<!DOCTYPE html>

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

Run the project:

At the beginning, there was no data. We added several pieces of test data:

Let's verify the result:

Click the corresponding column title to sort the column. Paging is also implemented. Of course, you can change the paging style by changing this option:

@ Html. PagedListPager (Model, page => Url. Action ("Index", new {page}), PagedListRenderOptions. Classic)

Here, I modified it.

@ Html. PagedListPager (Model, page => Url. Action ("Index", new {page}), PagedListRenderOptions. TwitterBootstrapPager)

This is the effect of the paging control.

Now, this article is over.

Conclusion: Paging and sorting are very important functions and must be mastered.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.