摘要
一直在用前后端分离,在一个后台管理的页面中,尝试封装了一个辅助类。
类
/// <summary> /// 分页viewmodel /// </summary> /// <typeparam name="T"></typeparam> public class PagedVM<T> where T : class, new() { private MysqlContext _mysqlContext; /// <summary> /// 构造函数注入数据库上下文 /// </summary> /// <param name="mysqlContext"></param> public PagedVM(MysqlContext mysqlContext) { _mysqlContext = mysqlContext; } public Expression<Func<T, bool>> Where { get; set; } /// <summary> /// 分页条开始索引 /// </summary> public int Start { get { return PageIndex - 10 > 0 ? PageIndex - 10 : 1; } } /// <summary> /// 分页条结束索引 /// </summary> public int End { get { return PageIndex + 10 > PageCount ? PageCount + 1 : PageIndex + 10; } } public int PageIndex { set; get; } = 1; public int PageSize { set; get; } = 10; public bool HavePrevious { get { return PageIndex > 1; } } public bool HaveNext { get { return PageIndex < PageCount; } } public int PageCount { get { return (int)Math.Ceiling(TotalCount * 1.0 / PageSize); } } public int TotalCount { get { return _mysqlContext.Set<T>().Count(); } } public List<T> Items { get { if (Where != null) { return _mysqlContext.Set<T>().Where(Where).ToList().Skip((PageIndex - 1) * PageSize).Take(PageSize).ToList(); } return _mysqlContext.Set<T>().ToList().Skip((PageIndex - 1) * PageSize).Take(PageSize).ToList(); } } }
分布试图分页条
<ul class="pagination pagination-lg navbar-right " style=""> @if (Model.HavePrevious) { <li class="previous"><a href="@Url.Content("~/home/index/")@(Model.PageIndex - 1)"> 上一页</a></li> } @for (int i = Model.Start; i < Model.End; i++) { if (i == Model.PageIndex) { <li class="active"><a href="@Url.Content("~/home/index/")@i">@i</a></li> } else { <li><a href="@Url.Content("~/home/index/")@i">@i</a></li> } } @if (Model.HaveNext) { <li class="next"><a href="@Url.Content("~/home/index/")@(Model.PageIndex+1)">下一页</a></li> } </ul>
测试