还在为mvc中没有一个分页htmlhelper 而烦恼吗
那我们何不自己写一个HtmlHelpe;
*首先命名空间一定是System.Web.Mvc
下面是源码
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Web; 6 7 namespace System.Web.Mvc 8 { 9 public static class MyHtmlHelper 10 { 11 //主要就是输出分页的超级链接的标签 12 //自定义分页Helper扩展 13 public static HtmlString ShowPageNavigate(this HtmlHelper htmlHelper, int currentPage, int pageSize, int totalCount) 14 { 15 var redirectTo = htmlHelper.ViewContext.RequestContext.HttpContext.Request.Url.AbsolutePath; 16 pageSize = pageSize <= 0 ? 3 : pageSize; 17 var totalPages = Math.Max((totalCount + pageSize - 1) / pageSize, 1); //总页数 18 var output = new StringBuilder(); 19 if (totalPages > 1) 20 { 21 //if (currentPage != 1) 22 {//处理首页连接 23 output.AppendFormat("<a class='pageLink' href='{0}?pageIndex=1&pageSize={1}'>首页</a> ", redirectTo, pageSize); 24 } 25 if (currentPage > 1) 26 {//处理上一页的连接 27 output.AppendFormat("<a class='pageLink' href='{0}?pageIndex={1}&pageSize={2}'>上一页</a> ", redirectTo, currentPage - 1, pageSize); 28 } 29 else 30 { 31 // output.Append("<span class='pageLink'>上一页</span>"); 32 } 33 34 output.Append(" "); 35 int currint = 5; 36 for (int i = 0; i <= 10; i++) 37 {//一共最多显示10个页码,前面5个,后面5个 38 if ((currentPage + i - currint) >= 1 && (currentPage + i - currint) <= totalPages) 39 { 40 if (currint == i) 41 {//当前页处理 42 //output.Append(string.Format("[{0}]", currentPage)); 43 output.AppendFormat("<a class='cpb' href='{0}?pageIndex={1}&pageSize={2}'>{3}</a> ", redirectTo, currentPage, pageSize, currentPage); 44 } 45 else 46 {//一般页处理 47 output.AppendFormat("<a class='pageLink' href='{0}?pageIndex={1}&pageSize={2}'>{3}</a> ", redirectTo, currentPage + i - currint, pageSize, currentPage + i - currint); 48 } 49 } 50 output.Append(" "); 51 } 52 if (currentPage < totalPages) 53 {//处理下一页的链接 54 output.AppendFormat("<a class='pageLink' href='{0}?pageIndex={1}&pageSize={2}'>下一页</a> ", redirectTo, currentPage + 1, pageSize); 55 } 56 else 57 { 58 //output.Append("<span class='pageLink'>下一页</span>"); 59 } 60 output.Append(" "); 61 if (currentPage != totalPages) 62 { 63 output.AppendFormat("<a class='pageLink' href='{0}?pageIndex={1}&pageSize={2}'>末页</a> ", redirectTo, totalPages, pageSize); 64 } 65 output.Append(" "); 66 } 67 output.AppendFormat("第{0}页 / 共{1}页", currentPage, totalPages);//这个统计加不加都行 68 69 return new HtmlString(output.ToString()); 70 } 71 } 72 }
调用
@Html.ShowPageNavigate(pageIndex,pageSize,totalCount) ;