在mvc中可以利用扩展方法添加HTML辅助器方法实现分页,这样就可以方便的实现分页代码的复用,代码如下
1 public static MvcHtmlString PageLinks(this HtmlHelper html, int curPage, int totalPage, Func<int, string> pageUrl) 2 { 3 StringBuilder result = new StringBuilder(); 4 int start = 1, end = totalPage; 5 start = curPage - 5 < 1 ? 1 : curPage - 5; 6 end = curPage + 5 > totalPage ? totalPage : curPage + 5; 7 8 if (curPage > 1) 9 { 10 TagBuilder prev = new TagBuilder("a"); 11 prev.MergeAttribute("href", pageUrl(curPage - 1)); 12 prev.InnerHtml = "<"; 13 result.Append(prev.ToString()); 14 } 15 16 17 for (int i = start; i <= end; i++) 18 { 19 TagBuilder tag = new TagBuilder("a"); 20 tag.InnerHtml = i.ToString(); 21 if (i != curPage) 22 { 23 tag.MergeAttribute("href", pageUrl(i)); 24 } 25 else 26 { 27 tag.MergeAttribute("href", "javascript:;"); 28 tag.AddCssClass("active"); 29 } 30 result.Append(tag.ToString()); 31 } 32 33 if (curPage < totalPage) 34 { 35 TagBuilder next = new TagBuilder("a"); 36 next.MergeAttribute("href", pageUrl(curPage - 1)); 37 next.InnerHtml = ">"; 38 result.Append(next.ToString()); 39 } 40 41 42 return MvcHtmlString.Create(result.ToString()); 43 }
添加以上代码后,这样在视图中创建分页链接时只需要简单的一行代码即可,如下所示,page为当前页,totalpage为总页数,第三个参数为生成的代码链接
@Html.PageLinks(page, totalPage, x => Url.Action("action", new { page=x;}))
原文地址:https://www.cnblogs.com/xiaoxiuyuan/p/9390145.html
时间: 2024-10-12 02:15:00