学习制作MVC4分页控件(上)

359 查看

浏览栏目下内容的时候肯定要用到分页,MVC4下没有带分页控件,那么就自己写一个HtmlHelper-Pager。写之前看了一些大神的分页控件,启发很大。先设想一下自己的分页控件

分页控件分普通分页(Pager)和Ajax分页(PagerAjax)两块。两块的显示相同,如图:

各部说明:

在开始写之前还要先有两个类:一个是分页设置类,一个是分页数据类。 

分页的设置类包含了常用的分页参数,是为了方便保存到数据库中,可以直接在栏目中设置该栏目下每页显示的记录数;记录的计量单位:是“条”还是“篇”;记录的名称是“新闻”、“文章”还是“教程”等。 

分页设置模型

分页数据类
用来提供记录列表和分页设置PagerData<T> 继承自 List<T>

想好直接之后,开始设置基础函数

1、pager的基础函数

复制代码 代码如下:
Pager(this HtmlHelper htmlHelper, string actionName, string controllerName, RouteValueDictionary routeValues, PagerConfig pageConfig, string ctrlId, string cssClass, int digitalLinkNum, bool showTotalRecord, bool showCurrentPage, bool showTotalPage, bool showSelect, bool showInput)

参数说明:
actionName-动作名称; 
controllerName-控制器名称; 
routeValues-路由参数; 
pageConfig-分页配置; 
ctrlId-分页控件Id; 
cssClass-分页控件css类名; 
digitalLinkNum-显示的数字链接个数; 
showTotalRecord-显示总记录数; 
showCurrentPage-显示当前页; 
showTotalPage-显示总页数; 
showSelect-显示页码下拉框; 
showInput-显示页码输入框。 

重载可能用到参数 
currentPage-当前页; 
totalPage-总页数; 
pageSize-每页显示记录数; 
totalRecord-总记录数; 
recordUnit-记录单位; 
recordName-记录名称; 

2、PagerAjax基础函数 

复制代码 代码如下:
public static MvcHtmlString PagerAjax(this HtmlHelper htmlHelper, string ctnrId, string actionName, string controllerName, RouteValueDictionary routeValues, PagerConfig pageConfig, string ctrlId, string cssClass, int digitalLinkNum, bool showTotalRecord, bool showCurrentPage, bool showTotalPage, bool showSelect, bool showInput)

参数说明:
ctnrId-内容容器Id。用于包裹ajax返回html的容器控件id 
其他参数与1、pager相同 
========================== 
基本的东西都准备好了,写代码就快了。 

右键点击Extensions文件夹,添加类PagerExtensions 

命名空间改为System.Web.Mvc,在该命名空间下先写PagerConfig,再写PagerData,代码都很简单。 

namespace System.Web.Mvc
{
  /// <summary>
  /// 分页配置
  /// </summary>
  public class PagerConfig
  {
    [Key]
    public int PagerConfigId { get; set; }
    /// <summary>
    /// 当前页
    /// </summary>
    [NotMapped]
    public int CurrentPage { get; set; }
    /// <summary>
    /// 每页记录数
    /// </summary>
    [Display(Name = "每页记录数", Description = "每页显示的记录数。")]
    [Required(ErrorMessage="×")]
    public int PageSize { get; set; }
    /// <summary>
    /// 总页数
    /// </summary>
    [NotMapped]
    public int TotalPage { get { return (int)Math.Ceiling(TotalRecord / (double)PageSize); } }
    /// <summary>
    /// 总记录数
    /// </summary>
    [NotMapped]
    public int TotalRecord { get; set; }
    /// <summary>
    /// 记录单位
    /// </summary>
    [Display(Name="记录单位",Description="记录的数量单位。如文章为“篇”;新闻为“条”")]
    [Required(ErrorMessage = "×")]
    public string RecordUnit { get; set; }
    /// <summary>
    /// 记录名称
    /// </summary>
    [Display(Name = "记录名称", Description = "记录的名称。如“文章”、“新闻”、“教程”等")]
    [Required(ErrorMessage = "×")]
    public string RecordName { get; set; }

    public PagerConfig()
    {
      CurrentPage = 1;
      PageSize = 20;
      RecordUnit = "条";
      RecordName = "记录";
    }
  }

  /// <summary>
  /// 分页数据
  /// </summary>
  public class PagerData<T> : List<T>
  {
    public PagerData(List<T> list, PagerConfig pagerConfig)
    {
      this.AddRange(list);
      Config = pagerConfig;
    }
    public PagerData(List<T> list, int currentPage, int pageSize, int totalRecord)
    {
      this.AddRange(list);
      Config.CurrentPage = currentPage;
      Config.PageSize = pageSize;
      Config.TotalRecord = totalRecord;
    }
    public PagerData(List<T> list, int currentPage, int pageSize, int totalRecord, string recordUnit, string recordName)
    {
      this.AddRange(list);
      Config.CurrentPage = currentPage;
      Config.PageSize = pageSize;
      Config.TotalRecord = totalRecord;
      Config.RecordUnit = recordUnit;
      Config.RecordName = recordName;
    }

    public PagerConfig Config { get; set; }
  }
}

下面到了关键部分: 
在文件PagerExtensions.cs底部再添加一个命名空间namespace System.Web.Mvc.Html。 
在里面添加静态类public static class PagerExtensions。 
在类中间添加函数public static MvcHtmlString Pager(……) 
代码也很容易就是用UrlHelper.Action生成链接的地址,再创建一个StringBuilder _strBuilder,不停的向里面附加html代码,最后使用return MvcHtmlString.Create(_strBuilder.ToString());返回MvcHtmlString。就是写的太乱啦 

public static MvcHtmlString Pager(this HtmlHelper htmlHelper, string actionName, string controllerName, RouteValueDictionary routeValues, PagerConfig pageConfig, string ctrlId, string cssClass, int digitalLinkNum, bool showTotalRecord, bool showCurrentPage, bool showTotalPage, bool showSelect, bool showInput)
    {
      UrlHelper _url = new UrlHelper(htmlHelper.ViewContext.RequestContext);
      StringBuilder _strBuilder = new StringBuilder("<div id=\"" + ctrlId + "\" class=\"" + cssClass + "\">");
      if (showTotalRecord) _strBuilder.Append("共" + pageConfig.TotalRecord + pageConfig.RecordUnit + pageConfig.RecordName + " ");
      if (showCurrentPage) _strBuilder.Append("每页" + pageConfig.PageSize + pageConfig.RecordUnit + " ");
      if(showTotalPage) _strBuilder.Append("第" + pageConfig.CurrentPage + "页/共" + pageConfig.TotalPage + "页 ");
      //首页链接
      if (pageConfig.CurrentPage > 1)
      {
        routeValues["page"] = 1;
        _strBuilder.Append("<a class=\"linkbtn\" href=\"" + _url.Action(actionName, controllerName, routeValues) + "\">首页</a>");
      }
      else _strBuilder.Append("<span class=\"btn\">首页</span>");
      //上一页
      if (pageConfig.CurrentPage > 1)
      {
        routeValues["page"] = pageConfig.CurrentPage - 1;
        _strBuilder.Append("<a class=\"linkbtn\" href=\"" + _url.Action(actionName, controllerName, routeValues) + "\">上一页</a>");
      }
      else _strBuilder.Append("<span class=\"btn\">上一页</span>");
      //数字导航开始
      int _startPage, _endPage;
      //总页数少于要显示的页数,页码全部显示
      if (digitalLinkNum >= pageConfig.TotalPage) { _startPage = 1; _endPage = pageConfig.TotalPage; }
      else//显示指定数量的页码
      {
        int _forward = (int)Math.Ceiling(digitalLinkNum / 2.0);
        if (pageConfig.CurrentPage > _forward)//起始页码大于1
        {
          _endPage = pageConfig.CurrentPage + digitalLinkNum - _forward;
          if (_endPage > pageConfig.TotalPage)//结束页码大于总页码结束页码为最后一页
          {
            _startPage = pageConfig.TotalPage - digitalLinkNum;
            _endPage = pageConfig.TotalPage;

          }
          else _startPage = pageConfig.CurrentPage - _forward;
        }
        else//起始页码从1开始
        {
          _startPage = 1;
          _endPage = digitalLinkNum;
        }
      }
      //向上…
      if (_startPage > 1)
      {
        routeValues["page"] = _startPage - 1;
        _strBuilder.Append("<a class=\"linkbatch\" href=\"" + _url.Action(actionName, controllerName, routeValues) + "\">…</a>");
      }
      //数字
      for (int i = _startPage; i <= _endPage; i++)
      {
        if (i != pageConfig.CurrentPage)
        {
          routeValues["page"] = i;
          _strBuilder.Append("<a class=\"linknum\" href=\"" + _url.Action(actionName, controllerName, routeValues) + "\">" + i.ToString() + "</a>");
        }
        else
        {
          _strBuilder.Append("<span class='currentnum'>" + i.ToString() + "</span>");
        }
      }
      //向下…
      if (_endPage < pageConfig.TotalPage)
      {
        routeValues["page"] = _endPage + 1;
        _strBuilder.Append("<a class=\"linkbatch\" href=\"" + _url.Action(actionName, controllerName, routeValues) + "\">…</a>");
      }
      ////数字导航结束
      //下一页和尾页
      if (pageConfig.CurrentPage < pageConfig.TotalPage)
      {
        routeValues["page"] = pageConfig.CurrentPage + 1;
        _strBuilder.Append("<a class=\"linkbtn\" href=\"" + _url.Action(actionName, controllerName, routeValues) + "\">下一页</a>");
        routeValues["page"] = pageConfig.TotalPage;
        _strBuilder.Append("<a class=\"linkbtn\" href=\"" + _url.Action(actionName, controllerName, routeValues) + "\">尾页</a>");
      }
      else _strBuilder.Append("<span class=\"btn\">下一页</span><span class=\"btn\">尾页</span>");
      //显示页码下拉框
      if (showSelect)
      {
        routeValues["page"] = "-nspageselecturl-";
        _strBuilder.Append(" 跳转到第<select id=\"nspagerselect\" data-url=\"" + _url.Action(actionName, controllerName, routeValues) + "\">");
        for (int i = 1; i <= pageConfig.TotalPage; i++)
        {
          if (i == pageConfig.CurrentPage) _strBuilder.Append("<option selected=\"selected\" value=\"" + i + "\">" + i + "</option>");
          else _strBuilder.Append("<option value=\"" + i + "\">" + i + "</option>");
        }
        _strBuilder.Append("</select>页");
        _strBuilder.Append("<script type=\"text/javascript\">$(\"#" + ctrlId + " #nspagerselect\").change(function () { location.href = $(\"#" + ctrlId + " #nspagerselect\").attr(\"data-url\").replace(\"-nspageselecturl-\", $(\"#" + ctrlId + " #nspagerselect\").val());});</script>");
      }
      //显示页码输入框
      if (showInput)
      {
        routeValues["page"] = "-nspagenumurl-";
        _strBuilder.Append("转到第<input id=\"nspagernum\" type=\"text\" data-url=\"" + _url.Action(actionName, controllerName, routeValues) + "\" />页");
        _strBuilder.Append("<script type=\"text/javascript\">$(\"#" + ctrlId + " #nspagernum\").keydown(function (event) {if (event.keyCode == 13) location.href = $(\"#" + ctrlId + " #nspagernum\").attr(\"data-url\").replace(\"-nspagenumurl-\", $(\"#" + ctrlId + " #nspagernum\").val()); });</script>");
      }
      _strBuilder.Append("</div>");
      return MvcHtmlString.Create(_strBuilder.ToString());
    }

PagerAjax跟Pager基本一样。不同点是在点击链接的时候Pager是转到相应页面,PagerAjax是在点击paer内的链接的时候利用jquery Post获取链接指定页面的html代码替换内容包裹容器的html。实际上就是这句jquery语句 

复制代码 代码如下:
<script type="text/javascript">$("#ctrlId a").click(function () {$.post($(this).attr("href"), function (data) {$("#ctnrId").html(data);});return false; });</script>

PagerAjax的整个内容 

public static MvcHtmlString PagerAjax(this HtmlHelper htmlHelper, string ctnrId, string actionName, string controllerName, RouteValueDictionary routeValues, PagerConfig pageConfig, string ctrlId, string cssClass, int digitalLinkNum, bool showTotalRecord, bool showCurrentPage, bool showTotalPage, bool showSelect, bool showInput)
    {
      UrlHelper _url = new UrlHelper(htmlHelper.ViewContext.RequestContext);
      StringBuilder _strBuilder = new StringBuilder("<div id=\"" + ctrlId + "\" class=\"" + cssClass + "\">");
      if (showTotalRecord) _strBuilder.Append("共" + pageConfig.TotalRecord + pageConfig.RecordUnit + pageConfig.RecordName + " ");
      if (showCurrentPage) _strBuilder.Append("每页" + pageConfig.PageSize + pageConfig.RecordUnit + " ");
      if (showTotalPage) _strBuilder.Append("第" + pageConfig.CurrentPage + "页/共" + pageConfig.TotalPage + "页 ");
      //首页链接
      if (pageConfig.CurrentPage > 1)
      {
        routeValues["page"] = 1;
        _strBuilder.Append("<a class=\"linkbtn\" href=\"" + _url.Action(actionName, controllerName, routeValues) + "\">首页</a>");
      }
      else _strBuilder.Append("<span class=\"btn\">首页</span>");
      //上一页
      if (pageConfig.CurrentPage > 1)
      {
        routeValues["page"] = pageConfig.CurrentPage - 1;
        _strBuilder.Append("<a class=\"linkbtn\" href=\"" + _url.Action(actionName, controllerName, routeValues) + "\">上一页</a>");
      }
      else _strBuilder.Append("<span class=\"btn\">上一页</span>");
      //数字导航开始
      int _startPage, _endPage;
      //总页数少于要显示的页数,页码全部显示
      if (digitalLinkNum >= pageConfig.TotalPage) { _startPage = 1; _endPage = pageConfig.TotalPage; }
      else//显示指定数量的页码
      {
        int _forward = (int)Math.Ceiling(digitalLinkNum / 2.0);
        if (pageConfig.CurrentPage > _forward)//起始页码大于1
        {
          _endPage = pageConfig.CurrentPage + digitalLinkNum - _forward;
          if (_endPage > pageConfig.TotalPage)//结束页码大于总页码结束页码为最后一页
          {
            _startPage = pageConfig.TotalPage - digitalLinkNum;
            _endPage = pageConfig.TotalPage;

          }
          else _startPage = pageConfig.CurrentPage - _forward;
        }
        else//起始页码从1开始
        {
          _startPage = 1;
          _endPage = digitalLinkNum;
        }
      }
      //向上…
      if (_startPage > 1)
      {
        routeValues["page"] = _startPage - 1;
        _strBuilder.Append("<a class=\"linkbatch\" href=\"" + _url.Action(actionName, controllerName, routeValues) + "\">…</a>");
      }
      //数字
      for (int i = _startPage; i <= _endPage; i++)
      {
        if (i != pageConfig.CurrentPage)
        {
          routeValues["page"] = i;
          _strBuilder.Append("<a class=\"linknum\" href=\"" + _url.Action(actionName, controllerName, routeValues) + "\">" + i.ToString() + "</a>");
        }
        else
        {
          _strBuilder.Append("<span class='currentnum'>" + i.ToString() + "</span>");
        }
      }
      //向下…
      if (_endPage < pageConfig.TotalPage)
      {
        routeValues["page"] = _endPage + 1;
        _strBuilder.Append("<a class=\"linkbatch\" href=\"" + _url.Action(actionName, controllerName, routeValues) + "\">…</a>");
      }
      ////数字导航结束
      //下一页和尾页
      if (pageConfig.CurrentPage < pageConfig.TotalPage)
      {
        routeValues["page"] = pageConfig.CurrentPage + 1;
        _strBuilder.Append("<a class=\"linkbtn\" href=\"" + _url.Action(actionName, controllerName, routeValues) + "\">下一页</a>");
        routeValues["page"] = pageConfig.TotalPage;
        _strBuilder.Append("<a class=\"linkbtn\" href=\"" + _url.Action(actionName, controllerName, routeValues) + "\">尾页</a>");
      }
      else _strBuilder.Append("<span class=\"btn\">下一页</span><span class=\"btn\">尾页</span>");
      //显示页码下拉框
      if (showSelect)
      {
        routeValues["page"] = "-nspageselecturl-";
        _strBuilder.Append(" 跳转到第<select id=\"nspagerselect\" data-url=\"" + _url.Action(actionName, controllerName, routeValues) + "\">");
        for (int i = 1; i <= pageConfig.TotalPage; i++)
        {
          if (i == pageConfig.CurrentPage) _strBuilder.Append("<option selected=\"selected\" value=\"" + i + "\">" + i + "</option>");
          else _strBuilder.Append("<option value=\"" + i + "\">" + i + "</option>");
        }
        _strBuilder.Append("</select>页");
        _strBuilder.Append("<script type=\"text/javascript\">$(\"#" + ctrlId + " #nspagerselect\").change(function () {$.post($(\"#" + ctrlId + " #nspagerselect\").attr(\"data-url\").replace(\"-nspageselecturl-\", $(\"#" + ctrlId + " #nspagerselect\").val()), function (data) {$(\"#" + ctnrId + "\").html(data);});});</script>");
      }
      //显示页码输入框
      if (showInput)
      {
        routeValues["page"] = "-nspagenumurl-";
        _strBuilder.Append(" 转到第<input id=\"nspagernum\" type=\"text\" data-url=\"" + _url.Action(actionName, controllerName, routeValues) + "\" />页");
        _strBuilder.Append("<script type=\"text/javascript\">$(\"#" + ctrlId + " #nspagernum\").keydown(function (event) {if (event.keyCode == 13) { $.post($(\"#" + ctrlId + " #nspagernum\").attr(\"data-url\").replace(\"-nspagenumurl-\", $(\"#" + ctrlId + " #nspagernum\").val()), function (data) {$(\"#" + ctnrId + "\").html(data);}); } });</script>");
      }
      _strBuilder.Append("<script type=\"text/javascript\">$(\"#" + ctrlId + " a\").click(function () {$.post($(this).attr(\"href\"), function (data) {$(\"#" + ctnrId + "\").html(data);});return false; });</script>");
      _strBuilder.Append("</div>");
      return MvcHtmlString.Create(_strBuilder.ToString());
    }



完工

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。