一个Asp.Net的显示分页方法 附加实体转换和存储过程 带源码下载

之前自己一直用Aspnetpager控件来显示项目中的分页,但是每次都要拖一个aspnetpager的控件进去,感觉很不舒服,因为现在自己写的webform都不用服务器控件了,所以自己仿照aspnetpager写了一个精简实用的返回分页显示的html方法,其他话不说了,直接上代码。
分页显示信息的实体类:


代码如下:

public class Pager
    {
        private string _firstPageText;
        /// <summary>
        /// 最前一页文字显示 默认显示为"首页"
        /// </summary>
        public string FirstPageText
        {
            get {
                return string.IsNullOrEmpty(_firstPageText)? "首页" : _firstPageText;
            }
            set {
                _firstPageText = value;
            }
        }
        private string _prePageText;
        /// <summary>
        /// 上一页文字显示 默认显示为"上一页"
        /// </summary>
        public string PrePageText
        {
            get
            {
                return string.IsNullOrEmpty(_prePageText) ? "上一页" : _prePageText;
            }
            set
            {
                _prePageText = value;
            }
        }
        private string _nextPageText;
        /// <summary>
        /// 下一页文字显示 默认显示为"下一页"
        /// </summary>
        public string NextPageText
        {
            get
            {
                return string.IsNullOrEmpty(_nextPageText) ? "下一页" : _nextPageText;
            }
            set
            {
                _nextPageText = value;
            }
        }
        private string _lastPageText;
        /// <summary>
        /// 末页文字显示 默认显示为"末页"
        /// </summary>
        public string LastPageText
        {
            get
            {
                return string.IsNullOrEmpty(_lastPageText) ? "末页" : _lastPageText;
            }
            set
            {
                _lastPageText = value;
            }
        }
        /// <summary>
        /// 总记录数
        /// </summary>
        public int RecordCount { get; set; }
        private int _pagesize=15;
        /// <summary>
        /// 每页分页尺寸 默认为15
        /// </summary>
        public int PageSize {
            get {
                return _pagesize == 0 ? 15 : _pagesize;
            }set{
                _pagesize = value;
            }
        }
        private int _pageIndex=1;
        /// <summary>
        /// 当前页码
        /// </summary>
        public int PageIndex {
            get {
                return _pageIndex == 0 ? 1 : _pageIndex;
            }
            set {
                _pageIndex = value;
            }
        }
        private int _maxShowPageSize = 10;
        /// <summary>
        /// 显示页码列表的最大个数 默认为10
        /// </summary>
        public int MaxShowPageSize {
            get {
                return _maxShowPageSize;
            }
            set {
                _maxShowPageSize = value;
            }
        }
        private string _queryStringName;
        /// <summary>
        /// 页码在浏览器中传值的名称  默认为page
        /// </summary>
        public string QueryStringName {
            get {
                return string.IsNullOrEmpty(_queryStringName)? "page" : _queryStringName;
            }
            set {
                _queryStringName = value;
            }
        }
        /// <summary>
        /// 页面的URL
        /// </summary>
        public string URL {
            get {
                string url = HttpContext.Current.Request.Url.AbsoluteUri;//当前页面绝对路径
                if (EnableUrlRewriting)//使用url重写
                {
                    url=url.Substring(0, url.LastIndexOf("/") + 1);//获取当前页面的目录路径
                    url += UrlRewritePattern;
                }
                else {//普通带问号的页面传值
                    //demo.aspx
                    //demo.aspx?a=1
                    //demo.aspx?page=1
                    //demo.aspx?a=2&page=1
                    if (url.Contains("aspx?"))
                    {
                        if (Regex.IsMatch(url,@"page=[0-9]*$",RegexOptions.IgnoreCase))//如果存在page=*的字符串
                        {
                            url = Regex.Replace(url, @"page=[0-9]*$", "", RegexOptions.IgnoreCase);//替换掉page=*的字符串
                        }
                        url += QueryStringName + "={0}";
                    }
                    else {
                        url += "?" + QueryStringName + "={0}";
                    }
                }
                return url;
            }
        }
        private bool _enableUrlRewriting;
        /// <summary>
        /// URL是否重写 默认为flase
        /// </summary>
        public bool EnableUrlRewriting {
            get {
                return (object)_enableUrlRewriting == null ? false : _enableUrlRewriting;
            }
            set {
                _enableUrlRewriting = value;
            }
        }
        /// <summary>
        /// 页面URL重写规则,将页码传值用{0}来代替  比如list-1-{0}.html,启用该功能需要将EnableUrlRewriting属性设为true
        /// </summary>
        public string UrlRewritePattern { get; set; }
        private string _className;
        /// <summary>
        /// 分页容器的css名称
        /// </summary>
        public string ClassName {
            get {
                return string.IsNullOrEmpty(_className) ? "paginator" : _className;
            }set{
                _className = value;
            }
        }
        private string _currentPageCss;
        /// <summary>
        /// 当前页面按钮css
        /// </summary>
        public string CurrentPageButtonCss {
            get {
                return string.IsNullOrEmpty(_currentPageCss) ? "cpb" : _currentPageCss;
            }set{
                _currentPageCss = value;
            }
        }
        private bool _showSpanText;
        /// <summary>
        /// Span 标签中文字信息是否显示 默认为false不显示
        /// </summary>
        public bool ShowSpanText {
            get {
                return (object)_showSpanText == null ? false : _showSpanText;
            }
            set {
                _showSpanText = value;
            }
        }
        private string _spanTextClass;
        /// <summary>
        /// 分页文字描述span标签css
        /// </summary>
        public string SpanTextClass {
            get {
                return string.IsNullOrEmpty(_spanTextClass) ? "stc" : _spanTextClass;
            }
            set {
                _spanTextClass = value;
            }
        }
        private string _submitButtonText;
        /// <summary>
        /// 确定按钮文字显示 默认显示"确定"
        /// </summary>
        public string SubmitButtonText {
            get {
                return string.IsNullOrEmpty(_submitButtonText) ? "确定" : _submitButtonText;
            }
            set {
                _submitButtonText = value;
            }
        }
    }

分页显示html代码的拼接方法:


代码如下:

public class SplitManager
    {
                public static string AspNetPagers(Pager pager)
        {
            StringBuilder sb = new StringBuilder();
            string attr="";
            int pagecount = 0;//当前页面的总层数
            int floorcount = 0;//分页的总层数
            int currentLastPage = 0;//当前最后一页的页码
            int pageNum = pager.RecordCount / pager.PageSize + 1;//总页数 1~24
            sb.AppendFormat("<div class=\"{0}\">\n", pager.ClassName);
            attr=pager.PageIndex==1?"disabled=disabled":"";//标志当前页第一页是否相等 来控制前俩个按钮的有效性
            sb.AppendFormat(GetAHtml(attr,string.Format(pager.URL,1),pager.FirstPageText));//添加最前一页的代码
            sb.AppendFormat(GetAHtml(attr, string.Format(pager.URL, pager.PageIndex-1), pager.PrePageText));//添加上一页的代码
            pagecount = pager.PageIndex/pager.MaxShowPageSize;//当前页数 0~1~2
            pagecount = pager.PageIndex % pager.MaxShowPageSize == 0 ? pagecount - 1 : pagecount;//清除当 当前页数为分页页码数的整数倍页时除数多一的状况
            floorcount = pageNum / pager.MaxShowPageSize;//页面层数 0~1~2
            currentLastPage=pageNum<pager.MaxShowPageSize * (pagecount + 1)?pageNum:pager.MaxShowPageSize * (pagecount + 1);
            if (pager.PageIndex > pager.MaxShowPageSize)//当当前序号大于每页页码个数时显示再前端...
            {
                sb.AppendFormat(GetAHtml("", string.Format(pager.URL, pager.MaxShowPageSize * pagecount), "..."));
            }
            for (int i = pager.MaxShowPageSize * pagecount + 1; i <= currentLastPage; i++)
            {
                if (i == pager.PageIndex)//判断循环页面是否为当前页
                {
                    sb.AppendFormat(GetSpanHtml(i, pager.CurrentPageButtonCss));
                }
                else {
                    sb.AppendFormat(GetAHtml("", string.Format(pager.URL, i),i.ToString()));
                }
            }
            if (pager.PageIndex <= pager.MaxShowPageSize * floorcount)//当当前序号小于倒数第二页页码时显示在后端...
            {
                sb.AppendFormat(GetAHtml("", string.Format(pager.URL, pager.MaxShowPageSize * (pagecount + 1) + 1), "..."));
            }
            attr = pager.PageIndex == pageNum ? "disabled=disabled" : "";//标志当前页最后一页是否相等 来控制后俩个按钮的有效性
            sb.AppendFormat(GetAHtml(attr, string.Format(pager.URL, pager.PageIndex+1), pager.NextPageText));//添加后一页的代码
            sb.AppendFormat(GetAHtml(attr, string.Format(pager.URL, pageNum), pager.LastPageText));//添加最后一页的代码
            if (pager.ShowSpanText)//是否显示分页文字span标签显示
            {
                sb.AppendFormat("<span class=\"" + pager.SpanTextClass + "\">共{0}页,每页{1}条记录 \n", pageNum, pager.PageSize);
                sb.AppendFormat("到第<input type=\"input\" id=\"jumpNum\" style=\"width:20px;\" name=\"jump\" value=\"{0}\" />页", pager.PageIndex == pageNum ? pageNum : pager.PageIndex + 1);
                sb.AppendFormat("<a href=\"#\" style=\"float:none;\" onclick=\"javascript:jump();\">" + pager.SubmitButtonText + "</a></span>\n");
                sb.Append(GetJumpScript(pager.URL));//添加按钮跳转的javascript代码
            }
            sb.AppendFormat("</div>");//
            return sb.ToString();
        }
        /// <summary>
        /// get the html of a label
        /// </summary>
        /// <param name="title">a's title</param>
        /// <param name="url">the url of a</param>
        /// <param name="attr">the attribute</param>
        /// <returns>return html string</returns>
        private static string GetAHtml(string attr,string url,string title)
        {
            return "<a " + attr + " href=\""+url+"\" style=\"margin-right:5px;\">"+title+"</a>\n";
        }
        /// <summary>
        /// get the html of a label
        /// </summary>
        /// <param name="num">the content of span</param>
        /// <param name="className">Class style Name</param>
        /// <returns>return html string </returns>
        private static string GetSpanHtml(int num, string className)
        {
            return "<span class=\"" + className + "\">" + num + "</span>\n";
        }
        /// <summary>
        /// 获取跳转的javascript代码
        /// </summary>
        /// <param name="url">当前分页的url规则</param>
        /// <returns>返回一个javascript代码</returns>
        private static string GetJumpScript(string url)
        {
            string scriptstr = "<script type=\"text/javascript\">\n" +
                        "function jump(){\n" +
                            "var jnum=document.getElementById(\"jumpNum\").value;\n" +
                            "if(isNaN(jnum)){\n"+
                                "alert(\"在跳转框中请输入数字!\");\n" +
                                "}\n"+
                            "else{\n"+
                                //"alert(jnum);\n" +
                                "location.href=String.format(\"" + url + "\",jnum);\n" +
                            "}\n"+
                        "}\n"+
                        "String.format = function() {\n"+
                            "if( arguments.length == 0 )\n"+
                                "return null; \n"+
                            "var str = arguments[0]; \n"+
                            "for(var i=1;i<arguments.length;i++) {\n"+
                                "var re = new RegExp('\\\\{' + (i-1) + '\\\\}','gm');\n"+
                                "str = str.replace(re, arguments[i]);\n"+
                            "}\n"+
                            "return str;\n"+
                        "}\n"+
                "</script>\n";
            return scriptstr;
        }
    }

最精简必要的几个参数传进去就能显示分页效果了:


代码如下:

protected string str = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            Pager pager = new Pager() { RecordCount = 350,
                PageSize = 15,
                MaxShowPageSize=10,
                PageIndex = Convert.ToInt32(Request.QueryString["page"]),
            ShowSpanText=true};
            str = SplitManager.AspNetPagers(pager);
        }

仿csdn的分页的效果图

供测试的css:


代码如下:

View Code
<style type="text/css">
        /*分页样式控制的开始*/
.paginator { font: 12px Arial, Helvetica, sans-serif;
             padding:10px 20px 10px 0;
             margin: 0px;}
.paginator a {border:solid 1px #ccc;
              color:#0063dc;
              cursor:pointer;
              text-decoration:none;}
.paginator a:visited {padding: 1px 6px;
                      border: solid 1px #ddd;
                      background: #f0f1f1;
                      text-decoration: none;}
.paginator .cpb {border:1px solid #14316b;
                 font-weight:700;
                 color:#f0f1f1;
                 background-color:#1f3d76;}
.paginator a:hover {border:solid 1px #14316b;
                    color:#14316b;
                    text-decoration:none;}
.paginator a,.paginator a:visited,.paginator .cpb,.paginator a:hover{float:left;
                                                                     height:16px;
                                                                     line-height:16px;
                                                                     min-width:10px;_width:10px;
                                                                     margin-right:5px;
                                                                     text-align:center;
                                                                     white-space:nowrap;
                                                                     font-size:12px;
                                                                     font-family:
                                                                     Arial,SimSun;
                                                                     padding:0 3px;}
.paginator .stc{color:#999;margin-left:20px;}
.paginator .stc a{margin-left:10px;}
/*分页样式控制的结束*/
    </style>

同时配合为了配合分页,再给出一个DataTable转泛型列表的一个方法和一个分页存储过程。
此转换方法需配合相应的实体类,并且实体类中需对象相应表的字段名,不区分大小写。


代码如下:

#region DataTable To List/Model
        /// <summary>
        /// DataTable To List
        /// </summary>
        /// <typeparam name="TType">object type</typeparam>
        /// <param name="dt">DataTable</param>
        /// <returns>return a List Model type</returns>
        public static List<T> DataTableToObjectList<T>(DataTable dt) where T : new()
        {
            DataRowCollection drc = dt.Rows;
            int columncount = drc.Count;
            List<T> result = new List<T>();    //declare the generic type of return
            Type type = typeof(T);
            PropertyInfo[] propertys = type.GetProperties(BindingFlags.IgnoreCase|BindingFlags.Instance|BindingFlags.Public|BindingFlags.SetProperty);   //get the collections of the model
            foreach (DataRow r in drc)
            {
                result.Add(DataRowToObjectModel<T>(r, propertys));
            }    
            return result;
        }
        /// <summary>
        /// DataRow To a Model
        /// </summary>
        /// <typeparam name="T">the type of Model</typeparam>
        /// <param name="r">DataRow</param>
        /// <param name="propertys">the object to Model</param>
        /// <returns>return a Model Type</returns>
        private static T DataRowToObjectModel<T>(DataRow r, PropertyInfo[] propertys) where T : new()
        {
            T t = new T();
            for (int i = 0; i < propertys.Length; i++)
            {
                object obj = r[propertys[i].Name];
                if (obj != null)
                {
                    if (propertys[i].PropertyType == typeof(int))
                        propertys[i].SetValue(t, PublicMethod.GetInt(obj), null);
                    if (propertys[i].PropertyType == typeof(string))
                        propertys[i].SetValue(t, obj.ToString(), null);
                    if (propertys[i].PropertyType == typeof(DateTime))
                        propertys[i].SetValue(t, PublicMethod.GetDateTime(obj), null);
                }
            }
            return t;
        }
        #endregion

分页存储过程。


代码如下:

CREATE PROCEDURE [dbo].[proc_SplitPage]
    -- Add the parameters for the stored procedure here
    @tblName   varchar(255),       -- 表名
    @strFields varchar(1000) = '*', -- 需要返回的列,默认*
    @strOrder varchar(255)='',      -- 排序的字段名,必填
    @strOrderType varchar(10)='ASC', -- 排序的方式,默认ASC
    @PageSize   int = 10,          -- 页尺寸,默认10
    @PageIndex int = 1,           -- 页码,默认1
    @strWhere varchar(1500) = '' -- 查询条件 (注意: 不要加 where)
AS
declare @strSQL   varchar(5000)
if @strWhere !=''
set @strWhere=' where '+@strWhere
set @strSQL=
'SELECT '+@strFields+' FROM ('+
    'SELECT ROW_NUMBER() OVER (ORDER BY '+@strOrder+' '+@strOrderType+') AS pos,'+@strFields+' '+
    'FROM '+@tblName+' '+@strWhere+
') AS sp
WHERE pos BETWEEN '+str((@PageIndex-1)*@PageSize+1)+' AND '+str(@PageIndex*@PageSize)
exec (@strSQL)

以上是全部代码,由于本人还是新手,请大家查找问题并指导,谢谢。
有些朋友需要源码的再此下载,方便测试

(0)

相关推荐

  • 简单好用的ASP.NET分页类(支持AJAX、自定义文字)

    在做网站没用 JS UI控件时 很实用 用法: var ps=new PageString(); /*可选参数*/ ps.SetIsEnglish = true;// 是否是英文 (默认:false) ps.SetIsShowText = true;//是否显示分页文字 (默认:true) //ps.TextFormat="" (默认值:<span class=\"pagetext\"><strong>总共</strong>:{0

  • asp.net jquery无刷新分页插件(jquery.pagination.js)

    采用Jquery无刷新分页插件jquery.pagination.js 实现无刷新分页效果 友情提示:本示例Handler中采用StringBuilder的append方法追加HTML,小数据量可以,但是大数据或是布局常变,建议返回JSON格式的数据,性能和灵活性更好! 1.插件参数列表  2.页面内容: 复制代码 代码如下: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Defaul

  • asp.net中使用自定义控件的方式实现一个分页控件的代码

    一.概述 在web开发中,常常需要显示一些数据,而为了方便排版及浏览,我们只需要显示所有记录中的一部分.一般情况下,我们采用分页来实现这个需求.实现分页的方法多种多样,在本文中,我们采用了一个分页空间来记录记录总数.当前页.总页数及页面大小等.为了有一个直观上的印象,先展示该控件运行后的效果,效果如下图所示: 二.实现方案 为了实现该效果图,在asp.net中,可以使用Custom Controls and User Controls两种方式,User Controls的实现方式及其简单,而且使

  • asp.net自定义分页控件示例

    一..ascx页面 复制代码 代码如下: <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Pagination.ascx.cs" Inherits="IOCS.WEB.UserControl.Pagination" %><link href="../Content/Css/Pager.css" rel="s

  • ASP.NET MVC 5使用X.PagedList.Mvc进行分页教程(PagedList.Mvc)

    ASP.NET MVC中进行分页的方式有多种,但在NuGet上使用最广泛的就是用PagedList.X.PagedList.Mvc进行分页.(原名为:PagedList.Mvc,但是2014年开始,作者将项目名称改名字为"X.PagedList.Mvc"),用这个插件的话会非常便利,大家可以试试,接下来将给大家讲下如何安装这个NuGet插件. ASP.NET MVC 5使用X.PagedList.Mvc进行分页教程(原名为PagedList.Mvc) 1.工具--NuGet 程序包管理

  • asp.net中如何调用sql存储过程实现分页

    首先看下面的代码创建存储过程 1.创建存储过程,语句如下: CREATE PROC P_viewPage @TableName VARCHAR(200), --表名 @FieldList VARCHAR(2000), --显示列名,如果是全部字段则为* @PrimaryKey VARCHAR(100), --单一主键或唯一值键 @Where VARCHAR(2000), --查询条件 不含'where'字符,如id>10 and len(userid)>9 @Order VARCHAR(100

  • asp.net利用后台实现直接生成html分页的方法

    本文实例讲述了asp.net利用后台实现直接生成html分页的方法,是一个比较实用的功能.分享给大家供大家参考之用.具体方法如下: 1.建立存储过程: ALTER procedure [dbo].[p_news_query] @Page int as begin select top 5 new_id,new_title,new_url,new_content_text,create_time,user_name from (select *,ROW_NUMBER() over(order by

  • Asp.Net数据控件引用AspNetPager.dll分页实现代码

    1.也许讲解有点初级,希望高手不要"喷"我,因为我知道并不是每一个人都是高手,我也怕高手们说我装13,小生不才: 2.如有什么不对的地方,还希望大家指出,一定虚心学习: 3.本文属于作者原创,尊重他人劳动成果,转载请注明作者,谢谢. 下面开讲: 第一步:首先是下载一个AspNetPager.dll 下载地址 AspNetPager.rar第二步:在项目的bin文件夹下引用AspNetPager.dll 如图: 第三步:在工具箱添加AspNetPager控件,如图: 接下来再如图: 这样

  • 分享一个asp.net pager分页控件

    效果: js: 复制代码 代码如下: $.fn.extend({ JPager: function (cfg, pageIndex, pageSize) { if (cfg && pageIndex > 0 && pageSize>0) { var token = "#" + this.attr("id"); this.empty(); var pageFirst = function () { $(token).JPag

  • ASP.NET MVC4 HtmlHelper扩展类,实现分页功能

    1.扩展HtmlHelper类方法ShowPageNavigate public static HtmlString ShowPageNavigate(this HtmlHelper htmlHelper, int currentPage, int pageSize, int totalCount) { var redirectTo = htmlHelper.ViewContext.RequestContext.HttpContext.Request.Url.AbsolutePath; page

随机推荐