程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> ASP.NET >> ASP.NET基礎 >> 一個Asp.Net的顯示分頁方法 附加實體轉換和存儲過程 帶源碼下載

一個Asp.Net的顯示分頁方法 附加實體轉換和存儲過程 帶源碼下載

編輯: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)

以上是全部代碼,由於本人還是新手,請大家查找問題並指導,謝謝。
有些朋友需要源碼的再此下載,方便測試

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved