打开Visual Studio 2017 选择 项目----->管理nuget包 其他版本也有
输入paged 下载安装 pagedList和pagedList.mvc
在model文件新建一个分页的类比如课程:
1 //要引入PagedList命名空间 2 using PagedList; 3 using System; 4 using System.Collections.Generic; 5 using System.Linq; 6 using System.Web; 7 8 namespace jiaowu.Models 9 { 10 public class ViewCourse 11 { 12 //创建课程对象 13 public IPagedList<Course> Course { get; set; } 14 /**条件**/ 15 //按姓名查询 16 public string Name { get; set; } 17 //排序条件 18 public string SortBy { get; set; } 19 20 } 21 }
在中控制器中
1 /// <summary> 2 /// 查询课程信息 3 /// </summary> 4 /// <param name="Name">课程名字</param> 5 /// <param name="page">当前页</param> 6 /// <returns></returns> 7 public ActionResult CourseList(string Name,int? pageIndex) 8 { 9 //查询所有的课程列表 10 var coures = en.Courses.OrderBy(m => m.Id); 11 //每页显示的数量 12 const int pageItems =4; 13 //当前页 14 int currentPage = (pageIndex ?? 1); 15 //查询所有的课程信息 16 IPagedList<Course> pageCoures = coures.ToPagedList(currentPage, pageItems); 17 //实例花一个ViewCourse的对象 18 ViewCourse vcourse = new ViewCourse(); 19 20 //判断用户名是否为空 21 if (string.IsNullOrEmpty(Name)) 22 { 23 //为空查询所有 24 vcourse.Course = pageCoures; 25 } 26 else 27 { 28 //不为空根据姓名查询 29 vcourse.Course = pageCoures.Where(m => m.Name == Name).ToPagedList(currentPage,pageItems); ; 30 } 31 return View(vcourse); 32 } 33
View视图中
1 <div style="width:1040px"> 2 <div style="float:right"> 3 @Html.PagedListPager(Model.Course, page => Url.Action("CourseList", new { Name = Model.Name, page })) 4 </div> 5 <div style="float:right;margin-top:28px;margin-right:10px"> 6 第 @(Model.Course.PageCount < Model.Course.PageNumber ? 0 : Model.Course.PageNumber) 页 共 @Model.Course.PageCount 页 7 </div> 8 9 </div>