MVC分页源码
全面兼容Bootstrap
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; namespace System.Web.Mvc { public static class TKHtml { public static HtmlString Pager(this HtmlHelper htmlHelper, string url, int currentPage, int pageSize, int totalCount) { var redirectTo = string.IsNullOrEmpty(url) ? htmlHelper.ViewContext.RequestContext.HttpContext.Request.Url.AbsolutePath : url; //每页行数 pageSize = pageSize == 0 ? 3 : pageSize; //当前页 currentPage = currentPage == 0 ? 1 : currentPage; //总页数 var totalPages = Math.Max((totalCount + pageSize - 1) / pageSize, 1); var output = new StringBuilder(); if (totalPages > 1) { output.AppendFormat("<li><a href='{0}'>首页</a></li> ", redirectTo); if (currentPage > 1) { if (currentPage - 1 == 1) { output.AppendFormat("<li><a href='{0}'>上一页</a></li> ", redirectTo); } else { output.AppendFormat("<li><a href='{0}_{1}'>上一页</a></li> ", redirectTo, currentPage - 1); } } output.Append(" "); int currint = 5; //一共最多显示10个页码,前面5个,后面5个 for (int i = 0; i <= 10; i++) { if ((currentPage + i - currint) >= 1 && (currentPage + i - currint) <= totalPages) { //当前页处理 if (currint == i) { output.AppendFormat("<li class='active'><a>{0}<span class='sr-only'>(current)</span></a></li> ", currentPage); } //一般页处理 else { if (currentPage + i - currint == 1) { output.AppendFormat("<li><a href='{0}'>{1}</a></li> ", redirectTo, currentPage + i - currint); } else { output.AppendFormat("<li><a href='{0}_{1}'>{2}</a></li> ", redirectTo, currentPage + i - currint, currentPage + i - currint); } } } output.Append(" "); } //处理下一页的链接 if (currentPage < totalPages) { output.AppendFormat("<li><a href='{0}_{1}'>下一页</a></li> ", redirectTo, currentPage + 1); } output.Append(" "); if (currentPage != totalPages) { output.AppendFormat("<li><a href='{0}_{1}'>末页</a></li> ", redirectTo, totalPages); } output.Append(" "); } //统计 output.AppendFormat("<li class='disabled'><a>第{0}页 / 共{1}页</a></li>", currentPage, totalPages); return new HtmlString(output.ToString()); } } }