首先从数据库获取数据
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using mvctest.Models;
namespace mvctest.customclass
{
public class getdataresource
{
public List<student> gd()
{
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<T>
{
//分页数据源
public IEnumerable<T> 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<T> dataSource)
{
this.PageSize = pageSize > 1 ? pageSize : 1;
this.DataSource = dataSource;
PageCount = (int)Math.Ceiling(dataSource.Count() / (double)pageSize);
}
//获取当前页数据
public IEnumerable<T> GetPagingData()
{
return DataSource.Skip((PageIndex - 1) * PageSize).Take(PageSize);
}
}
}
控制器中的代码
public ActionResult pagehelp(int pageIndex = 1)
{
getdataresource gd=new getdataresource();
PagingHelper<student> StudentPaging = new PagingHelper<student>(3, gd.gd());
StudentPaging.PageIndex = pageIndex;//指定当前页
return View(StudentPaging);//返回分页器实例到视图
}
对应视图
@using mvctest.Models
@using mvctest.customclass
@model mvctest.PagingHelper<student>
@{
ViewBag.Title = "Pagehelper";
}
<h2>Index</h2>
@foreach (var Data in Model.GetPagingData())
{
<p>ID:@Data.id Name:@Data.name</p>
}
<p>
@if (Model.HasPrev)
{
<a href="@Url.Action("pagehelp", "test", new { pageIndex = Model.PageIndex - 1 })">上一页</a>
}
else
{
<em style="color:Gray">上一页</em>
}
@if (Model.HasNext)
{
<a href="@Url.Action("pagehelp", "test", new { pageIndex = Model.PageIndex + 1 })">下一页</a>
}
else
{
<em style="color:Gray">下一页</em>
}
</p>