core mvc 分页
看了下XPAGE感觉还是用的不太爽,自己写了个,不处理数据,只根据参数生成分页的html代码,样式是bootstrap的,需要的小伙伴拿走吧。
public static IHtmlContent Pager(this IHtmlHelper html, long totalCount, int pageSize, string pageStr) { if (totalCount < 1) return new HtmlString(string.Empty); var totalPages = (int)Math.Ceiling(totalCount / (double)pageSize); //总页数 var dicRoute = html.ViewContext.RouteData.Values; var strQuery = html.ViewContext.HttpContext.Request.Query; int pageIndex; if (dicRoute.ContainsKey(pageStr)) { if (!int.TryParse(dicRoute[pageStr].ToString(), out pageIndex)) pageIndex = 1; } else { if (!int.TryParse(strQuery[pageStr].ToString(), out pageIndex)) pageIndex = 1; } if (pageIndex < 1) pageIndex = 1; if (pageIndex > totalPages) pageIndex = totalPages; foreach (var key in dicRoute.Keys) { if (string.IsNullOrEmpty(key) || !strQuery.ContainsKey(key)) continue; if (!strQuery.TryGetValue(key, out var values)) continue; if (values.Count == 1 && !string.IsNullOrEmpty(values)) { dicRoute[key] = strQuery[key]; } } var sbOut = new StringBuilder(); sbOut.Append("<nav aria-label=\"Page navigation\">"); sbOut.Append("<ul class=\"pagination\">"); if (totalPages > 1) { sbOut.Append("<li"); sbOut.Append(pageIndex == 1 ? " class=\"disabled\">" : ">"); dicRoute[pageStr] = 1; sbOut.Append(pageIndex == 1 ? "<a>首页</a>" : GetString(html.RouteLink("首页", dicRoute))); sbOut.Append("</li>"); var pre = pageIndex - 1; if (pre < 1) pre = 1; sbOut.Append("<li"); sbOut.Append(pageIndex == 1 ? " class=\"disabled\">" : ">"); dicRoute[pageStr] = pre; sbOut.Append(pageIndex == 1 ? "<a>上一页</a>" : GetString(html.RouteLink("上一页", dicRoute))); sbOut.Append("</li>"); var nex = pageIndex + 1; if (nex > totalPages) nex = totalPages; sbOut.Append("<li"); sbOut.Append(pageIndex == totalPages ? " class=\"disabled\">" : ">"); dicRoute[pageStr] = nex; sbOut.Append(pageIndex == totalPages ? "<a>下一页</a>" : GetString(html.RouteLink("下一页", dicRoute))); sbOut.Append("</li>"); sbOut.Append("<li"); sbOut.Append(pageIndex == totalPages ? " class=\"disabled\">" : ">"); dicRoute[pageStr] = totalPages; sbOut.Append(pageIndex == totalPages ? "<a>尾页</a>" : GetString(html.RouteLink("尾页", dicRoute))); sbOut.Append("</li>"); } sbOut.AppendFormat("<li><a>共{0}条数据</a></li>", totalCount); sbOut.Append("</ul>"); sbOut.Append("</nav>"); return new HtmlString(sbOut.ToString()); }
说明下,totalCount是总条数,pageSize是每页条数,pageStr是页参数的 key 如:http://123.com/?page=4 pageStr就是 page
使用如下
@Html.Pager(10, 1, "page")
以上代码中的 GetString 方法请阅读第一篇文章
基本翻译
n. 寻呼机,呼机
n. (Pager)人名;(德)帕格