欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

ASP.NET MVC分页和排序功能实现

程序员文章站 2023-12-11 22:48:10
分页和排序,应该是软件开发中,需要必知必会的技能了,对于分页,网上很多教程,当然,别人终究是别人的,只有自己理解,会了,并且吸收之后,再用自己的语言,传授出来,这才是硬道理...

分页和排序,应该是软件开发中,需要必知必会的技能了,对于分页,网上很多教程,当然,别人终究是别人的,只有自己理解,会了,并且吸收之后,再用自己的语言,传授出来,这才是硬道理。好了,废话说多了。现在我们进入正题: 

这里,我打算使用ef code-first方式分页控件就是用pagedlist.mvc,来做分页,对于排序,实现的思路是,加载数据出来之后,默认是升序排序,然后我们点击一下相应的列标题,就按照该字段降序排序,查数据。思路明确了,就开始干吧! 

1.首先新建一个空白的mvc项目,在model文件夹里,新建一个student实体

ASP.NET MVC分页和排序功能实现

student实体中的代码: 

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.添加ef引用之后,我们在根目录下,在创建一个文件夹map,在里面创建一个类studentmap 

ASP.NET MVC分页和排序功能实现

studentmap类的代码: 

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()
 {
  //配置主键
  this.haskey(s => s.id);

  //把id列设置为自增列
  this.property(s => s.id).hasdatabasegeneratedoption(databasegeneratedoption.identity);
  //配置列
  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.在根目录下,再新建一个文件夹dbhelper,在里面新建一个类studentdbcontext 

ASP.NET MVC分页和排序功能实现

studentdbcontext类的代码: 

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)
 {
  //因为这里只有一个实体,就不搞的那么复杂了,不用反射来做。直接添加单个实体的配置
  modelbuilder.configurations.add(new studentmap());
  base.onmodelcreating(modelbuilder);
 }
 }
} 

然后在配置文件中加上: 

<connectionstrings>
<add name="dbconnectionstring" connectionstring="server=.;database=mystudentdb;uid=sa;pwd=password_1" providername="system.data.sqlclient"/>
</connectionstrings> 

具体的位置在这: 

ASP.NET MVC分页和排序功能实现

4.好了,现在实体和数据库的配置都写好了,现在我们使用数据库迁移技术【migrations】来自动生成数据库,首先打开程序包管理控制台。
添加一行语句:enable-migrations,然后按回车键:

ASP.NET MVC分页和排序功能实现

这个时候,就在我们程序中生成了一个文件夹migrations,里面有一个类configuration: 

ASP.NET MVC分页和排序功能实现

修改configuration类中的代码:把 automaticmigrationsenabled 设置为true;并添加一句代码,让迁移过程中,没有数据丢失:  
automaticmigrationdatalossallowed = false;

ASP.NET MVC分页和排序功能实现

然后在程序包管理控制台中接着输入:
 update-database  -verbose 

注意: 【-verbose和database之间有空格】,之所以输入-verbose就是可以在控制台看到生成的sql语句: 

pm> update-database -verbose
using 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> 

打开数据库,我们看到,就生成我们想要的数据库和表了: 

ASP.NET MVC分页和排序功能实现

既然要分页,就开始引入分页控件吧,引入pagedlist.mvc 

ASP.NET MVC分页和排序功能实现

5.新建一个空白模板的student控制器。

ASP.NET MVC分页和排序功能实现

控制器里面就是我们主要的逻辑代码了:

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>
 /// 首页【查询分页数据】
 /// </summary>
 /// <param name="sortby">根据什么排序</param>
 /// <param name="currentsort">当前排序字段</param>
 /// <param name="page">当前页</param>
 /// <returns></returns>
 public actionresult index(string sortby,string currentsort,int? page)
 {
  int pageindex = 1;
  int pagesize = 5;
  //判断page是否有值,有的话就给值,没有就赋值1
  pageindex = page.hasvalue ? convert.toint32(page) : 1;
  viewbag.currentsort = sortby; 
//这句必须要,否则刚开始是空的,报错,就不能循环了。
sortby = string.isnullorempty(sortby) ? "name" : sortby; //如果sortby为空,就设置为name,下面设置的时候,默认按照名称排序
 
  ipagedlist<student> lststudent = null;
  switch (sortby)
  {
  case "name":
   //如果sortby==currentsort,就按照对应字段降序排列,并分页。否则升序。
   if (sortby.equals(currentsort))
   {
   lststudent = db.set<student>().
    orderbydescending(s => s.name).
    topagedlist(pageindex, pagesize);    //根据一热心博友的建议,加上了这句,点击相应的列,升序降序循环。                 viewbag.currentsort = null;
   }
   else
   {
   lststudent = db.set<student>().
    orderby(s => s.name).
    topagedlist(pageindex, pagesize);
   }
   break;

  case "sex":
   //如果sortby==currentsort,就按照对应字段降序排列,并分页。否则升序。
   if (sortby.equals(currentsort))
   {
   lststudent = db.set<student>().
    orderbydescending(s => s.sex).
    topagedlist(pageindex, pagesize); //根据一热心博友的建议,加上了这句,点击相应的列,升序降序循环。                 viewbag.currentsort = null; 
   }
   else
   {
   lststudent = db.set<student>().
    orderby(s => s.sex).
    topagedlist(pageindex, pagesize);
   }
   break;

  case "email":
   //如果sortby==currentsort,就按照对应字段降序排列,并分页。否则升序。
   if (sortby.equals(currentsort))
   {
   lststudent = db.set<student>().
    orderbydescending(s => s.email).
    topagedlist(pageindex, pagesize); //根据一热心博友的建议,加上了这句,点击相应的列,升序降序循环。                 viewbag.currentsort = null; 
   }
   else
   {
   lststudent = db.set<student>().
    orderby(s => s.email).
    topagedlist(pageindex, pagesize);
   }
   break;

  case "age":
   //如果sortby==currentsort,就按照对应字段降序排列,并分页。否则升序。
   if (sortby.equals(currentsort))
   {
   lststudent = db.set<student>().
    orderbydescending(s => s.age).
    topagedlist(pageindex, pagesize); //根据一热心博友的建议,加上了这句,点击相应的列,升序降序循环。                 viewbag.currentsort = null; 
   }
   else
   {
   lststudent = db.set<student>().
    orderby(s => s.age).
    topagedlist(pageindex, pagesize);
   }
   break;

  default:
   //如果sortby==currentsort,就按照对应字段降序排列,并分页。否则升序。
   if (sortby.equals(currentsort))
   {
   lststudent = db.set<student>().
    orderbydescending(s => s.name).
    topagedlist(pageindex, pagesize); //根据一热心博友的建议,加上了这句,点击相应的列,升序降序循环。                 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");
 }
 }
} 

创建相对应的index视图和addstudent视图: 

ASP.NET MVC分页和排序功能实现

index视图: 

@using pagedlist.mvc;@*//引入分页的组件*@
@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> 

<h2>index</h2>

<p>
 @html.actionlink("create new", "create")
</p>
@using(html.beginform("index","employee",formmethod.get))
{ 
<table class="table">
 <tr>
 <th>
  @* 通过创建匿名对象,传递参数到控制器中,new { sortby = "name", currentsort = viewbag.currentsort }*@
  @*参数的大小写无所谓,只要和控制器名称一样就行,sortby,currentsort*@
  @html.actionlink("name", "index", new { sortby = "name", currentsort = viewbag.currentsort })
 </th>
 <th>
  @html.actionlink("sex", "index", new { sortby = "sex", currentsort = viewbag.currentsort })
 </th>
 <th>
  @html.actionlink("email", "index", new { sortby = "email", currentsort = viewbag.currentsort })
 </th>
 <th>
  @html.actionlink("age", "index", new {sortby = "age", currentsort = viewbag.currentsort })
 </th>
 <th></th>
 </tr>

@foreach (var item in model) {
 <tr>
 <td>
  @html.displayfor(modelitem => item.name)
 </td>
 <td>
  @html.displayfor(modelitem => item.sex)
 </td>
 <td>
  @html.displayfor(modelitem => item.email)
 </td>
 <td>
  @html.displayfor(modelitem => item.age)
 </td>
 <td>
  
 </td>
 </tr>
}

</table>
}
<div id="paging" style="text-align:center">
 @*总页数是否小于当前页,小于就说明没数据,赋值0,否则赋值pagenumber*@ 
 page @(model.pagecount< model.pagenumber?0:model.pagenumber) of @model.pagecount 
 @html.pagedlistpager(model, page => url.action("index", new { page}),pagedlistrenderoptions.classic)
</div>

addstudent视图: 

@model pagingandsortinginmvc.models.student

@{
 viewbag.title = "addstudent";
}

<h2>addstudent</h2>


@using (html.beginform()) 
{
 @html.antiforgerytoken()
 
 <div class="form-horizontal">
 <h4>student</h4>
 <hr />
 @html.validationsummary(true, "", new { @class = "text-danger" })
 <div class="form-group">
  @html.labelfor(model => model.name, htmlattributes: new { @class = "control-label col-md-2" })
  <div class="col-md-10">
  @html.editorfor(model => model.name, new { htmlattributes = new { @class = "form-control" } })
  @html.validationmessagefor(model => model.name, "", new { @class = "text-danger" })
  </div>
 </div>

 <div class="form-group">
  @html.labelfor(model => model.sex, htmlattributes: new { @class = "control-label col-md-2" })
  <div class="col-md-10">
  @html.editorfor(model => model.sex, new { htmlattributes = new { @class = "form-control" } })
  @html.validationmessagefor(model => model.sex, "", new { @class = "text-danger" })
  </div>
 </div>

 <div class="form-group">
  @html.labelfor(model => model.email, htmlattributes: new { @class = "control-label col-md-2" })
  <div class="col-md-10">
  @html.editorfor(model => model.email, new { htmlattributes = new { @class = "form-control" } })
  @html.validationmessagefor(model => model.email, "", new { @class = "text-danger" })
  </div>
 </div>

 <div class="form-group">

  @html.labelfor(model => model.age, htmlattributes: new { @class = "control-label col-md-2" })
  <div class="col-md-10">
  @html.editorfor(model => model.age, new { htmlattributes = new { @class = "form-control" } })
  @html.validationmessagefor(model => model.age, "", new { @class = "text-danger" })
  </div>
 </div>

 <div class="form-group">
  <div class="col-md-offset-2 col-md-10">
  <input type="submit" value="create" class="btn btn-default" />
  </div>
 </div>
 </div>
}

<div>
 @html.actionlink("back to list", "index")
</div>

<script src="~/scripts/jquery-1.10.2.min.js"></script>
<script src="~/scripts/jquery.validate.min.js"></script>
<script src="~/scripts/jquery.validate.unobtrusive.min.js"></script> 

接着修改一下布局页: 

<!doctype html>
<html>
<head>
 <meta charset="utf-8" />
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>@viewbag.title - my asp.net application</title>
 <link href="~/content/site.css" rel="stylesheet" type="text/css" />
 <link href="~/content/bootstrap.min.css" rel="stylesheet" type="text/css" />
 <script src="~/scripts/modernizr-2.6.2.js"></script>
</head>
<body>
 <div class="navbar navbar-inverse navbar-fixed-top">
 <div class="container">
  <div class="navbar-header">
  <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
   <span class="icon-bar"></span>
   <span class="icon-bar"></span>
   <span class="icon-bar"></span>
  </button>
  @html.actionlink("application name", "index", "home", new { area = "" }, new { @class = "navbar-brand" })
  </div>
  <div class="navbar-collapse collapse">
  <ul class="nav navbar-nav">
   @html.actionlink("student list","index")
   @html.actionlink("add student ", "addstudent")
  </ul>
  </div>
 </div>
 </div>

 <div class="container body-content">
 @renderbody()
 <hr />
 <footer>
  <p>© @datetime.now.year - my asp.net application</p>
 </footer>
 </div>

 <script src="~/scripts/jquery-1.10.2.min.js"></script>
 <script src="~/scripts/bootstrap.min.js"></script>
</body>
</html> 

修改一下默认路由: 

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

 

运行项目:

ASP.NET MVC分页和排序功能实现

刚开始没有任何数据,我们添加几条测试数据:

ASP.NET MVC分页和排序功能实现

我们来验证一下,结果:

ASP.NET MVC分页和排序功能实现

看到了么,点击相应的列标题就可以进行排序了。分页也实现了。当然分页的样式可以通过改变这个选项:

@html.pagedlistpager(model, page => url.action("index", new { page}),pagedlistrenderoptions.classic)

这里,我修改了一下

@html.pagedlistpager(model, page => url.action("index", new { page}),pagedlistrenderoptions.twitterbootstrappager)

分页控件的效果就是这样了。

ASP.NET MVC分页和排序功能实现

好了,这篇文章到此结束。

总结:分页和排序是很重要的功能,需要熟练掌握。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

上一篇:

下一篇: