分页的功能可以用sql的存储过程完成,但实际上,在sql中生成的存储过程引用到EF模型中以后,也就是一个方法。那么,我们在项目中,在DAL层直接做成一个方法就可以了。
效果(我做的每页显示1行):
分页万能公式:(页码-1)*行数
DAL层代码:
/// <summary>
/// 分页
/// </summary>
/// <param name="pageSize">行数</param>
/// <param name="pageIndex">页码</param>
/// <param name="pageCount>总页数</param>
/// <returns>集合和总页数</returns>
public static List<Student> Select(int pageSize,int pageIndex,out int pageCount)
{
using (ExamDBEntities db = new ExamDBEntities())
{
var stus = db.Student;//只是查询,并没有使用数据。
pageCount = (int)Math.Ceiling(stus.Count() * 1.0 / pageSize);
return stus.OrderBy(p => p.StuID).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
}
}
要注意,pageCount形参要带out关键字,具体out关键字什么用处可以自己百度。只需要记住,调用的时候,不管是形参还是实参都需要加out关键字,否则无法识别。
BLL层:略。
控制器代码:
//调用操作方法时传参,因为做上一页下一页时,需要传参
public ActionResult Index(int pageSize=1,int pageIndex=1)
{
int pageCount = 0;
var stus = StudentManager.GetStuByPage(pageSize, pageIndex, out pageCount);
ViewBag.pSize = pageSize;
ViewBag.pIndex = pageIndex;
ViewBag.pCount = pageCount;//因为DAL里面return了list,就没办法再return一个int的pageCount,所以用out很关键
return View(stus);//前台用强类型遍历
}
view代码:
<div>
<span>共 @ViewBag.pCount 页</span>
<span>第 <input type="text" id="pageIndex" onblur="pageIndex" value="@ViewBag.pIndex" style="width:15px;text-align:center" /> 页</span>
@{
if (ViewBag.pIndex == 1)
{
@Html.ActionLink("下一页", "Index", new { pageSize = ViewBag.pSize, pageIndex = ViewBag.pIndex + 1 })
}
else if (ViewBag.pIndex == ViewBag.pCount)
{
@Html.ActionLink("上一页", "Index", new { pageSize = ViewBag.pSize, pageIndex = ViewBag.pIndex - 1 })
}
else
{
@Html.ActionLink("上一页", "Index", new { pageSize = ViewBag.pSize, pageIndex = ViewBag.pIndex - 1 })
@Html.ActionLink("下一页", "Index", new { pageSize = ViewBag.pSize, pageIndex = ViewBag.pIndex + 1 })
}
}
</div>
要考虑一下什么时候上一页/下一页是没有的,什么时候是两个都要有的
前台script代码:
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$("#pageIndex").blur(function () {
var aa = $("#pageIndex").val();
$.ajax({
url: "/Students/Index",
type: "post",
data: { "pageIndex": aa },
success: function (data) {
if (data != null) {
$("#stus").html(data);
}
}
})
})
</script>