1、分页实体类
public class PageDto { public int PageIndex { get; set; } public int PageSize { get; set; } public int PageCount { get; set; } public int TotalCount { get; set; } }
后端代码
public async TaskIndex() { var page = HttpContext.Request.Query["page"].ToString(); var pageSize = HttpContext.Request.Query["pageSize"].ToString(); var searchDto = new FileSearchDto() { PageIndex = string.IsNullOrWhiteSpace(page) ? 1 : Convert.ToInt32(page), PageSize = string.IsNullOrWhiteSpace(pageSize) ? 5 : Convert.ToInt32(pageSize) }; var results = await _service.GetPageList(searchDto); var model = new FileListViewModel() { Results = results }; return View(model); }
2、视图
@using System.Text;@model BaseService.PageDto@if (Model.TotalCount > Model.PageSize){ var controller = Url.ActionContext.RouteData.Values["controller"]; var action = Url.ActionContext.RouteData.Values["action"]; var url = "/" + controller + "/" + action; var querys = Url.ActionContext.HttpContext.Request.Query; StringBuilder sb = new StringBuilder(); sb.AppendFormat("/{0}/{1}?", controller, action); if (querys != null && querys.Count > 0) { foreach (var item in querys) { if (!item.Key.Equals("page")) { sb.AppendFormat("{0}={1}", item.Key, item.Value); sb.Append("&"); } } } sb.Append("page"); url = sb.ToString();}
显示第 @((Model.PageIndex - 1) * Model.PageSize + 1) - @(Model.PageIndex * Model.PageSize > Model.TotalCount ? Model.TotalCount : Model.PageIndex * Model.PageSize) 条记录,共 @Model.TotalCount 条记录
@if (Model.PageIndex > 1) {- } else {
- } @{ int pagesizeshow = 6;//每次显示分页按钮数量 int pagemin = Model.PageIndex - (int)(pagesizeshow / 2); int pagemax = Model.PageIndex + (int)(pagesizeshow / 2); if (Model.PageIndex + (int)(pagesizeshow / 2) >= Model.PageCount) { pagemin = Model.PageCount - (int)(pagesizeshow / 2); pagemax = Model.PageCount; } if (Model.PageIndex <= (int)(pagesizeshow / 2)) { pagemin = 1; pagemax = pagesizeshow; } if (pagemin <= 0) { pagemin = 1; } if (pagemax >= Model.PageCount) { pagemax = Model.PageCount; } if (pagemin + pagesizeshow >= Model.PageCount) { pagemin = (Model.PageCount - pagesizeshow) >= 1 ? (Model.PageCount - pagesizeshow) : pagemin; } if (pagemin == pagemax) {
- @pagemin
} else { for (int i = pagemin; i <= pagemax; i++) {- class="active" }>@i
} } } @if (Model.PageIndex < Model.PageCount) {- } else {
- }
3、调用
@Html.Partial("~/Views/Pager/Create.cshtml", Model.Results.Page)