public class PageHelper { ////// 标签 /// public string Tag { get; set; } ////// 选中的标签样式 /// public string TagCurr { get; set; } ////// 分页的路径 /// public string Url { get; set; } ////// 当前页 /// public int PageIdnex { get; set; } ////// 总页数 /// public int PageCount { get; set; } ////// 实现分页算法 /// ///public string CreatePage( ) { //1.1当前页大于总页数 if (PageIdnex > PageCount) return null; StringBuilder sb = new StringBuilder(); //1.2当总页数小于5条时,显示全部的页码 if (PageCount <= 5) { //拼接页码 for (int i = 1; i <= PageCount; i++) { if (PageIdnex == i) { //拼接当前页 sb.Append($"{i}"); } else { sb.Append($"{i}"); } } return sb.ToString(); } else { //2.2 总页数大于5,当前页小于4时 if (PageIdnex <= 4) { //2.2.1 当前页靠近尾页 if (PageCount - PageIdnex <= 3) { //拼接第一页 sb.Append($"1..."); for (int i = PageIdnex - 1; i <= PageCount; i++) { if (PageIdnex == i) { //拼接当前页 sb.Append($"{i}"); } else { sb.Append($"{i}"); } } } else { //2.2.2当前页靠近首页 for (int i = 1; i <= PageIdnex + 2; i++) { if (PageIdnex == i) { sb.Append($"{i}"); } else { sb.Append($"{i}"); } } //拼接最后一页 sb.Append($"...{PageCount}"); } } else { //2.3 总页数大于5,当前页大于4时 sb.Append($"1..."); //2.3.1 当前页大于4,当前页离尾页很近 if (PageCount - PageIdnex <= 2) { for (int i = PageIdnex - 2; i <= PageCount; i++) { if (PageIdnex == i) { sb.Append($"{i}"); } else { sb.Append($"{i}"); } } } else { //2.3.2当前页在中间 for (int i = PageIdnex - 2; i < PageIdnex + 2; i++) { if (PageIdnex == i) { sb.Append($"{i}"); } else { sb.Append($"{i}"); } } sb.Append($"...{PageCount}"); } } return sb.ToString(); }
控制器 var list = new List<string>();
for (int i = 1; i <= 100; i++) { list.Add("北京朝阳区" + i); } int pageSzie = 10; int pageCount = 0; if (list.Count % pageSzie == 0) { pageCount = list.Count / pageSzie; } else { pageCount = (list.Count / pageSzie) + 1; } PageHelper ph = new PageHelper { Tag = "a", TagCurr = "curr", Url = "/testpage/list/", PageIndex=pageIndex, PageCount=pagecount
}; var strHtml = ph.CreatePage(); var pageList = list.Skip((pageIndex - 1) * pageSzie).Take(pageSzie).ToList(); ViewBag.StrHtml = strHtml; ViewBag.PageList = pageList;
JS
function fenye_ok() { pager("/TestPage/list", 1);}function pager(href, pageIndex) { var num = $("#num").val(); $("#div-load").load("/TestPage/list", { "pageIndex": pageIndex, "num": num }, function () { });}