zoukankan      html  css  js  c++  java
  • ASP.NET MVC使用HTML辅助器实现分页

    在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;}))
  • 相关阅读:
    单例实现c++
    c++智能指针实现方式1
    c++中处理输入输出的方法
    makefile函数
    5. Longest Palindromic Substring
    go 语言中常用的包
    ubuntu14.04 boost动态库找不到 libboost_system.so.1.58.0
    boost-asio-cpp-network-programming阅读笔记
    链接-装载-库,读书笔记
    leecode第二百一十七题(存在重复元素)
  • 原文地址:https://www.cnblogs.com/xiaoxiuyuan/p/9390145.html
Copyright © 2011-2022 走看看