通過HtmlHelper中PagingHelper類實現分頁方法介紹

來源:互聯網
上載者:User
這篇文章主要為大家詳細介紹了MVC HtmlHelper擴充,實現分頁功能,具有一定的參考價值,感興趣的小夥伴們可以參考一下

MVC HtmlHelper擴充類PagingHelper實現分頁功能,供大家參考,具體內容如下

using System;using System.Collections.Generic;using System.Collections.Specialized;using System.Linq;using System.Text;using System.Web;using System.Web.Mvc;using System.Web.Routing;namespace HtmlHelperMvc.Models{ /// <summary> /// 分頁類如果一個頁面顯示兩個列表只需要複製該類到項目中重新命名一個就可以 /// </summary> public static class PagingHelper {  #region 屬性Property  /// <summary>  /// 當前頁碼  /// </summary>  private static int? _currentPage = null;  /// <summary>  /// 當前頁碼  /// </summary>  public static int CurrentPage  {   get   {    return _currentPage ?? 1;   }   set   {    _currentPage = value;   }  }  /// <summary>  /// 每頁記錄條數  /// </summary>  private static int? _pageSize = null;  /// <summary>  /// 每頁記錄條數  /// </summary>  public static int PageSize  {   get   {    return _pageSize ?? 15;   }   set   {    _pageSize = value;   }  }  /// <summary>  /// 是否顯示上一頁  /// </summary>  public static bool HasPreviousPage  {   get   {    return (CurrentPage > 1);   }  }  /// <summary>  /// 是否顯示下一頁  /// </summary>  public static bool HasNextPage  {   get   {    return (CurrentPage < TotalPages);   }  }  /// <summary>  /// 當前頁:  /// </summary>  public static string CurrentPageDisplayName { get; set; }  /// <summary>  /// 每頁顯示:  /// </summary>  public static string PageSizeDisplayName { get; set; }  public static string FirstDisplayName { get; set; }  public static string PreDisplayName { get; set; }  public static string NextDisplayName { get; set; }  public static string LastDisplayName { get; set; }  public static string TotalCountDisplayName { get; set; }  public static string TotalPagesDisplayName { get; set; }  /// <summary>  /// 總條數  /// </summary>  public static int TotalCount  {   get;   set;  }  public static int TotalPages  {   get   {    return (int)Math.Ceiling(TotalCount / (double)PageSize);    //return (TotalCount % PageSize == 0 ? TotalCount / PageSize : TotalCount / PageSize + 1);   }  }  /// <summary>  /// 設定分頁url eg:/Admin/Product/Index  /// </summary>  public static string PagingUrl  {   get;   set;  }  /// <summary>  /// 預設page,設定分頁參數名 eg:/Admin/Product/Index?PagingParamName=1  /// </summary>  public static string PagingParamName  {   get;   set;  }  #endregion  #region Paging String  /// <summary>  /// MVC分頁 如果用jquery分頁只需要class不需要href,用以下實現:  /// $(".class值").live("click", function () {  /// var page = $(this).attr("pagingParamName值");  /// $("#order").html("").load("/Customer/Order?page="+page);  /// });live自動給遍曆增加事件  /// </summary>  /// <param name="html"></param>  /// <param name="htmlAttributes">new {@class="grey",pagingParamName="page",href="/Admin/Product/Index" rel="external nofollow" } pagingParamName預設page,匿名類添加控制項屬性</param>  /// <returns></returns>  public static MvcHtmlString Paging(this System.Web.Mvc.HtmlHelper html, object htmlAttributes)  {   RouteValueDictionary values = new RouteValueDictionary(htmlAttributes);   #region 屬性賦值   if (values["href"] != null)   {    PagingUrl = values["href"].ToString();   }   if (values["pagingParamName"] != null)   {    PagingParamName = values["pagingParamName"].ToString();    values.Remove("pagingParamName");   }   else   {    PagingParamName = "page";   }   #endregion   #region 分頁最外層p/span   TagBuilder builder = new TagBuilder("p");//span   //建立Id,注意要先設定IdAttributeDotReplacement屬性後再執行GenerateId方法.    //builder.IdAttributeDotReplacement = "_";   //builder.GenerateId(id);   //builder.AddCssClass("");   //builder.MergeAttributes(values);   builder.InnerHtml = PagingBuilder(values);   #endregion   return MvcHtmlString.Create(builder.ToString(TagRenderMode.Normal));//解決直接顯示html標記  }  private static string PagingBuilder(RouteValueDictionary values)  {   #region 條件搜尋時包括其他參數   StringBuilder urlParameter = new StringBuilder();   NameValueCollection collection = HttpContext.Current.Request.QueryString;   string[] keys = collection.AllKeys;   for (int i = 0; i < keys.Length; i++)   {    if (keys[i].ToLower() != "page")    {     urlParameter.AppendFormat("&{0}={1}", keys[i], collection[keys[i]]);    }   }   #endregion   //CurrentPage = Convert.ToInt32(HttpContext.Current.Request.QueryString["page"] ?? "0");   StringBuilder sb = new StringBuilder();   #region 分頁統計   sb.AppendFormat("Total  {0}   Records Page  {1} of  {2}   ", TotalCount, CurrentPage, TotalPages);   #endregion   #region 首頁 上一頁   sb.AppendFormat(TagBuilder(values, 1, " First"));   //sb.AppendFormat("<a href={0}?page=1{1}>First</a> ",url,urlParameter);   if (HasPreviousPage)   {    sb.AppendFormat(TagBuilder(values, CurrentPage - 1, " Prev "));    //sb.AppendFormat("<a href={0}?page={1}{2}>Prev</a> ", url, CurrentPage - 1, urlParameter);   }   #endregion   #region 分頁邏輯   if (TotalPages > 10)   {    if ((CurrentPage + 5) < TotalPages)    {     if (CurrentPage > 5)     {      for (int i = CurrentPage - 5; i <= CurrentPage + 5; i++)      {       sb.Append(TagBuilder(values, i, i.ToString()));      }     }     else     {      for (int i = 1; i <= 10; i++)      {       sb.Append(TagBuilder(values, i, i.ToString()));      }     }     sb.Append("... ");    }    else    {     for (int i = CurrentPage - 10; i <= TotalPages; i++)     {      sb.Append(TagBuilder(values, i, i.ToString()));     }    }   }   else   {    for (int i = 1; i <= TotalPages; i++)    {     sb.Append(" " + TagBuilder(values, i, i.ToString()) + "&nbsp");    }   }   #endregion   #region 下一頁 末頁   if (HasNextPage)   {    sb.AppendFormat(TagBuilder(values, CurrentPage + 1, "Next"));    //sb.AppendFormat("<a href={0}?page={1}{2}>Next</a> ", url, CurrentPage + 1, urlParameter);   }   sb.AppendFormat(TagBuilder(values, TotalPages, "Last"));   //sb.AppendFormat("<a href={0}?page={1}{2}>Last</a>",url,TotalPages,urlParameter);   #endregion   return sb.ToString();  }  private static string TagBuilder(RouteValueDictionary values, int i, string innerText)  {   values[PagingParamName] = i;   TagBuilder tag = new TagBuilder("a");   if (PagingUrl != null)   {    values["href"] = PagingUrl + "?" + PagingParamName + "= " + i + "   ";   }   if (CurrentPage == i && innerText != " First" && innerText != " Last")   {    values["id"] = "on";   }   else   {    tag.Attributes["id"] = "";   }   tag.MergeAttributes(values);   tag.SetInnerText(innerText);   return tag.ToString();  }  #endregion }}

後台Controller代碼

//// GET: /Home/public ActionResult Index(int? page){ page = page ?? 1; PagingHelper.CurrentPage = Convert.ToInt32(page); PagingHelper.PageSize = 20; //{擷取資料集的中條數,以及分頁的資料集} PagingHelper.TotalCount = 2000; return View();}

前台頁面代碼

@{ ViewBag.Title = "Index";}@using HtmlHelperMvc.Models;<h2>Index</h2><hr /><style type="text/css"> #on {  color: #FFF;  background-color: #337AB7;  border-color: #337AB7; } .pagination a {  margin-right: 3px;  padding: 5px 10px;  font-size: 12px;  text-decoration: none;  background-color: #fff;  border: 1px solid #ddd;  cursor: pointer;  display: inline-block;  border-radius: 3px; } a {  color: #337ab7;  text-decoration: none; } a {  background-color: transparent; } * {  -webkit-box-sizing: border-box;  -moz-box-sizing: border-box;  box-sizing: border-box; }</style><script src="~/Scripts/jquery-1.8.2.js"></script><script type="text/javascript"> $(function () {  $(".pagination .active").live("click", function () {   $("#page").val($(this).attr("page"));   $("#form_Submit").submit();  }); });</script><form id="form_Submit" action="/Home/Index" method="post"> <p class="fix">  <p class="page">   <p class="pagination pagination-sm pull-right" id="pagep" style="margin: 0px 0;">    <input type="hidden" id="page" name="page" value="@PagingHelper.CurrentPage" />    @Html.Paging(new { @class = "active" })   </p>  </p> </p></form>

最終:

【相關推薦】

1. ASP.NET免費視頻教程

2. 極客學院ASP.NET視頻教程

3. ASP.NET視頻教程

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.