发布时间:2020-02-18 20:58:47来源:本站阅读(829)
看了下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 方法
private static string GetString(IHtmlContent content)
{
using (var writer = new System.IO.StringWriter())
{
content.WriteTo(writer, HtmlEncoder.Default);
return writer.ToString();
}
}
1828
1928
1482
854
1540
1201
1100
1596
717
1761
9598
6001
5528
5122
4573
4276
3421
3340
3339
3274