MVC htmlhelper extension class (paginghelper) implements paging function

Time:2021-10-7

MVC htmlhelper extension class paginghelper implements paging function for your reference. The specific contents are as follows

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>
 ///Paging class if a page displays two lists, you only need to copy the class to the project and rename one
 /// </summary>
 public static class PagingHelper
 {
  #Region property
  /// <summary>
  ///Current page number
  /// </summary>
  private static int? _currentPage = null;
  /// <summary>
  ///Current page number
  /// </summary>
  public static int CurrentPage
  {
   get
   {
    return _currentPage ?? 1;
   }
   set
   {
    _currentPage = value;
   }
  }
  /// <summary>
  ///Number of records per page
  /// </summary>
  private static int? _pageSize = null;
  /// <summary>
  ///Number of records per page
  /// </summary>
  public static int PageSize
  {
   get
   {
    return _pageSize ?? 15;
   }
   set
   {
    _pageSize = value;
   }
  }
  /// <summary>
  ///Show previous page
  /// </summary>
  public static bool HasPreviousPage
  {
   get
   {
    return (CurrentPage > 1);
   }
  }
  /// <summary>
  ///Show next page
  /// </summary>
  public static bool HasNextPage
  {
   get
   {
    return (CurrentPage < TotalPages);
   }
  }
  /// <summary>
  ///Current page:
  /// </summary>
  public static string CurrentPageDisplayName { get; set; }
  /// <summary>
  ///Display per page:
  /// </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>
  ///Total number
  /// </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>
  ///Set paging URL eg: / admin / product / index
  /// </summary>
  public static string PagingUrl
  {
   get;
   set;
  }
  /// <summary>
  ///Default page, set paging parameter name eg: / admin / product / index? Pagingparamname = 1
  /// </summary>
  public static string PagingParamName
  {
   get;
   set;
  }
  #endregion
  #region Paging String
  /// <summary>
  ///MVC paging if jQuery paging only needs class, not href, use the following implementation:
  ///$(". Class value"). Live ("click", function()){
  ///Var page = $(this). Attr ("pagingparamname value");
  /// $("#order").html("").load("/Customer/Order?page="+page);
  /// }); Live automatically adds events to the traversal
  /// </summary>
  /// <param name="html"></param>
  ///< param name = "htmlattributes" > New {@ class = "grey", pagingparamname = "page", href = "/ admin / product / index" rel = "external nofollow"} pagingparamname default page, add control attributes to anonymous classes < / param >
  /// <returns></returns>
  public static MvcHtmlString Paging(this System.Web.Mvc.HtmlHelper html, object htmlAttributes)
  {
   RouteValueDictionary values = new RouteValueDictionary(htmlAttributes);
   #Region attribute assignment
   if (values["href"] != null)
   {
    PagingUrl = values["href"].ToString();
   }
   if (values["pagingParamName"] != null)
   {
    PagingParamName = values["pagingParamName"].ToString();
    values.Remove("pagingParamName");
   }
   else
   {
    PagingParamName = "page";
   }
   #endregion
   #Region paging outermost div / span
   TagBuilder builder = new TagBuilder("div");//span
   //When creating ID, please set the idattributedotreplacement attribute before executing the generateid method 
   //builder.IdAttributeDotReplacement = "_";
   //builder.GenerateId(id);
   //builder.AddCssClass("");
   //builder.MergeAttributes(values);
   builder.InnerHtml = PagingBuilder(values);
   #endregion
   return MvcHtmlString.Create(builder.ToString(TagRenderMode.Normal));// Solve the problem of displaying HTML tags directly
  }
  private static string PagingBuilder(RouteValueDictionary values)
  {
   #Region includes other parameters when searching by criteria
   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 paging statistics
   sb.AppendFormat("Total &nbsp;{0} &nbsp; Records Page &nbsp;{1} of &nbsp;{2} &nbsp; ", TotalCount, CurrentPage, TotalPages);
   #endregion
   #Region home page Previous
   sb.AppendFormat(TagBuilder(values, 1, " First"));
   //sb.AppendFormat("<a href={0}?page=1{1}>First</a>&nbsp;",url,urlParameter);
   if (HasPreviousPage)
   {
    sb.AppendFormat(TagBuilder(values, CurrentPage - 1, " Prev "));
    //sb.AppendFormat("<a href={0}?page={1}{2}>Prev</a>&nbsp;", url, CurrentPage - 1, urlParameter);
   }
   #endregion
   #Region paging logic
   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("...&nbsp;");
    }
    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("&nbsp;" + TagBuilder(values, i, i.ToString()) + "&nbsp");
    }
   }
   #endregion
   #Region last page of next page
   if (HasNextPage)
   {
    sb.AppendFormat(TagBuilder(values, CurrentPage + 1, "Next"));
    //sb.AppendFormat("<a href={0}?page={1}{2}>Next</a>&nbsp;", 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 + "&nbsp;&nbsp;&nbsp;";
   }
   if (CurrentPage == i && innerText != " First" && innerText != " Last")
   {
    values["id"] = "on";
   }
   else
   {
    tag.Attributes["id"] = "";
   }
   tag.MergeAttributes(values);
   tag.SetInnerText(innerText);
   return tag.ToString();
  }
  #endregion
 }
}

Background controller code

//
// GET: /Home/

public ActionResult Index(int? page)
{
 page = page ?? 1;
 PagingHelper.CurrentPage = Convert.ToInt32(page);
 PagingHelper.PageSize = 20;

 //{get the number of entries in the dataset and the paged dataset}

 PagingHelper.TotalCount = 2000;
 return View();
}

Foreground page code


@{
 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 action="/Home/Index" method="post">
 <div>
  <div>
   <div style="margin: 0px 0;">
    <input type="hidden" name="page" value="@PagingHelper.CurrentPage" />
    @Html.Paging(new { @class = "active" })
   </div>
  </div>
 </div>
</form>

Final rendering:

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support developpaer.