首先从数据库获取数据
using System;using System.Collections.Generic;using System.Linq;using System.Web;using mvctest.Models;namespace mvctest.customclass{ public class getdataresource { public Listgd() { Model1 db=new Model1(); var q = from p in db.Students select p; return q.ToList(); } }}
分页代码:网上复制的
using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace mvctest{ // 分页器Code public class PagingHelper{ //分页数据源 public IEnumerable DataSource { get; private set; } //每页显示记录的数量 public int PageSize { get; private set; } //当前页数 public int PageIndex { get; set; } //分页总页数 public int PageCount { get; private set; } //是否有前一页 public bool HasPrev { get { return PageIndex > 1; } } //是否有下一页 public bool HasNext { get { return PageIndex < PageCount; } } //构造函数 public PagingHelper(int pageSize, IEnumerable dataSource) { this.PageSize = pageSize > 1 ? pageSize : 1; this.DataSource = dataSource; PageCount = (int)Math.Ceiling(dataSource.Count() / (double)pageSize); } //获取当前页数据 public IEnumerable GetPagingData() { return DataSource.Skip((PageIndex - 1) * PageSize).Take(PageSize); } }}
控制器中的代码
public ActionResult pagehelp(int pageIndex = 1) { getdataresource gd=new getdataresource(); PagingHelperStudentPaging = new PagingHelper (3, gd.gd()); StudentPaging.PageIndex = pageIndex;//指定当前页 return View(StudentPaging);//返回分页器实例到视图 }
对应视图
@using mvctest.Models@using mvctest.customclass@model mvctest.PagingHelper@{ ViewBag.Title = "Pagehelper";} Index
@foreach (var Data in Model.GetPagingData()){ID:@Data.id Name:@Data.name
}@if (Model.HasPrev) { 上一页 } else { 上一页 } @if (Model.HasNext) { 下一页 } else { 下一页 }