浅析ASP.NET高效分页的实现过程

开发 后端
本文将介绍的是ASP.NET高效分页的实现过程,实例是以上一页和下一页的方式实现的。

本文要实现的是以上一页和下一页的方式实现的ASP.NET高效分页,至于以1、2、3、4这样的形式显示的ASP.NET高效分页,还有待于作者的进一步研究ASP.NET高效分页后实现。

简单、高效这是我们追求的分页效果。

现在有三种很常见的分页:

1、分页用的html和后台代码都自己写 ,设计和代码一般都只对应某个网页,难以在其他页面很好的重用

2、最简单的当然是数据控件自带的分页功能,他的那些缺陷已经被讨论很多年了,我就不重复了,相信稍微有点魄力和职业态度的程序员都不会用那个分页

3、自制的分页控件,可以实现代码和设计的分离,可以在多个页面重用控件,但是缺陷是:每个页面都得调用控件而且还要在页面的后台代码里初始化控件,例如向控件里传送总页数、当前分页序号、页面大小等

综合以上分析,我打算自己做个简单的分页控件,思路如下:

1、首先必须实现分页时代码和设计的分离,例如“下一页”,“上一页”,他们的样式写在一个文件里,而把控制他们怎么显示写在另一个文件里,例如,到了最后一页,“最后一页”这个按钮不能用。所以我写了个template.html文件,这个描述了分页时的样式

  1. Code  
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
  3. <html xmlns="http://www.w3.org/1999/xhtml"> 
  4. <head> 
  5.     <title></title> 
  6. </head> 
  7. <body> 
  8.     <div style="width: 100%; height: 30px; overflow: hidden; clear: both; font-size: 12px;" id="MyPagingString{10}"> 
  9.         <div style="float: left; width: 50px; line-height: 20px; text-align: center; height: 20px;  
  10.             border: 1px solid #d8dfea; margin-left: 15px; cursor: pointer; display: {0}"  
  11.             onmouseover="p.on({1},this)" onmouseout="p.out({1},this)" onclick="p.direct({1},'first','{10}')"> 
  12.             第一页  
  13.         </div> 
  14.         <div style="float: left; width: 50px; line-height: 20px; text-align: center; height: 20px;  
  15.             border: 1px solid #d8dfea; margin-left: 15px; cursor: pointer; display: {0}"  
  16.             onmouseover="p.on({2},this)" onmouseout="p.out({2},this)" onclick="p.direct({2},'previous','{10}')"> 
  17.             上一页  
  18.         </div> 
  19.         <div style="float: left; width: 50px; line-height: 20px; text-align: center; height: 20px;  
  20.             border: 1px solid #d8dfea; margin-left: 15px; cursor: pointer; display: {0}"  
  21.             onmouseover="p.on({3},this)" onmouseout="p.out({3},this)" onclick="p.direct({3},'next','{10}')"> 
  22.             下一页  
  23.         </div> 
  24.         <div style="float: left; width: 65px; line-height: 20px; text-align: center; height: 20px;  
  25.             border: 1px solid #d8dfea; margin-left: 15px; cursor: pointer; display: {0}"  
  26.             onmouseover="p.on({4},this)" onmouseout="p.out({4},this)" onclick="p.direct({4},'end','{10}',{11})"> 
  27.             最后一页  
  28.         </div> 
  29.         <div style="float: left; height: 20px; line-height: 20px; margin-left: 20px; display: {9}"> 
  30.             每页记录:<span style=" color:Red;">{5}</span>  当前页: <span style=" color:red;">{6} </span> 总页数: <span style=" color:Red;">{7}</span>  总记录数: <span style=" color:Red;">{8}</span> 
  31.         </div> 
  32.     </div> 
  33.  
  34.     <script type="text/javascript"> 
  35.         var divTab='MyPagingString{10}';  
  36.         var div=[{1},{2},{3},{4}];  
  37.         var p = {  
  38.             init: function() {  
  39.                     var pstr=document.getElementById(divTab).getElementsByTagName("div");  
  40.                     if (!div[0]){  
  41.                        pstr[0].style.color = '#ccc';}  
  42.                     if (!div[1]){  
  43.                        pstr[1].style.color = '#ccc';}  
  44.                     if (!div[2]){  
  45.                        pstr[2].style.color = '#ccc';}  
  46.                     if (!div[3]){  
  47.                        pstr[3].style.color = '#ccc';}  
  48.             },  
  49.             on: function(v, this_) {  
  50.                 if (v) {  
  51.                     this_.style.backgroundColor = '#3b5998'this_.style.color = '#fff';  
  52.             }},  
  53.             out: function(v, this_) {  
  54.                 if (v) {  
  55.                     this_.style.backgroundColor = '#fff'this_.style.color = '#000';  
  56.             }},  
  57.             direct:function(v,t,i){  
  58.             if (!v) {return;}  
  59.             var index=parseInt(i.split('|')[1]);  
  60.             var temp=i.split('|')[0]+'_paging_index=';  
  61.             var _cookie=document.cookie;  
  62.             var cookiekey=_cookie.substring(_cookie.indexOf(temp)+temp.length,_cookie.indexOf(";",_cookie.indexOf(temp)));  
  63.             document.cookie="paging_table="+i.split('|')[0];  
  64.             switch(t){  
  65.             case "first":  
  66.             document.cookie=temp+"0";  
  67.             break;  
  68.             case "previous":   
  69.             document.cookie=temp+(--index);  
  70.             break;  
  71.             case "next":   
  72.             document.cookie=temp+(++index);  
  73.             break;  
  74.             case "end":  
  75.             document.cookie=temp+arguments[3];  
  76.             break;  
  77.             }  
  78.             document.cookie="paging=1";  
  79.             document.forms[0].submit();  
  80.             }};  
  81.         p.init();  
  82.     </script> 
  83. </body> 
  84. </html> 

当程序第一次加载时,从硬盘读取分页模板文件template.html并且放入缓存,如果第二次有分页请求时就从缓存读取,
如果,template.html,被修改则再次从硬盘读取,类似asp.net里的配置文件读取机制,

缓存代码如下:

  1. Code  
  2. public static string GetPageHtml()  
  3.     {  
  4.         pagingHtml = (string)(HttpContext.Current.Cache["paging"]);  
  5.         if (string.IsNullOrEmpty(pagingHtml))  
  6.         {  
  7.             string path = null;  
  8.             CacheDependency cd;  
  9.             path = GetPagingTemplePath();  
  10.             cd = new CacheDependency(path);  
  11.             ReadPagingHtmlsFromDisk(path);     
  12.             HttpContext.Current.Cache.Insert("paging", pagingHtml, cd);  
  13.         }  
  14.         return pagingHtml;  
  15.     } 

2、对数据源的获取的sql实现了优化,下面是两种常用的分页语句,第二条语句的优势在于:

not in 会引起全表扫描,而且不会使用聚集索引,而第二条语句没有这样的缺陷

  1. select top size  * from table where id not in (select top  index*size id from table )  
  2. lect top size  * from table where id > (select max (id) from (select top  index*size id from tableas T ) 

对用户输入的sql语句,例如“select * from table”自动优化成上面的第二种格式

下面这个方法实现了复杂sql语句转化

  1. Code  
  2. public static string AnalyticsSql(string sql, int index, int size)  
  3.     {  
  4.         string keyid = null, columns = null, table = null, orderby = null, wherestr = null, originalSql = null;  
  5.         originalSql = sql;  
  6.         originalSql = originalSql.Replace(originalSql.Substring(originalSql.IndexOf(" select ") + 8, originalSql.IndexOf(" from ") - 8 - originalSql.IndexOf(" select ")), " count(*) ");  
  7.         if (sql.IndexOf(" * ") != -1)  
  8.         {  
  9.             if (sql.IndexOf("|") != -1)  
  10.             {  
  11.                 keyid = sql.Substring(sql.IndexOf("|") + 1, sql.IndexOf(" ", sql.IndexOf("|")) - sql.IndexOf("|") - 1);  
  12.             }  
  13.             else 
  14.             {  
  15.                 keyid = "id";  
  16.             }  
  17.             columns = "*";  
  18.         }  
  19.         else 
  20.         {  
  21.             keyid = sql.Substring(sql.IndexOf("select") + 6, sql.IndexOf(",") - sql.IndexOf("select") - 6);  
  22.             columns = sql.Substring(sql.IndexOf("select") + 6, sql.IndexOf(" from ") - 6 - sql.IndexOf("select"));  
  23.         }  
  24.         if (sql.IndexOf(" where ") != -1)  
  25.         {  
  26.             wherestr = " where ";  
  27.             if (sql.IndexOf(" order ") != -1)  
  28.                 wherestr += sql.Substring(sql.IndexOf(" where ") + 7, sql.IndexOf(" order ") - sql.IndexOf(" where ") - 7);  
  29.             else 
  30.                 wherestr += sql.Substring(sql.IndexOf(" where ") + 7);  
  31.         }  
  32.         table = GetSqlTable(sql);  
  33.         if (sql.IndexOf(" order ") != -1)  
  34.         {  
  35.             orderby = sql.Substring(sql.LastIndexOf("by") + 2);  
  36.         }  
  37.         else 
  38.         {  
  39.             orderby = keyid;  
  40.         }  
  41.  
  42.         sql = "select top " + size.ToString() + " " + columns + " from " + table + " where  " + keyid + ">isnull((select max (" + keyid + ") from (select top " + (index * size).ToString() + " " + keyid.ToString() + " from " + table + wherestr + " order by " + orderby + ") as T),0) order by " + keyid;  
  43.         return originalSql + ";" + sql;  
  44.     } 

需要补充的是分页排序时id问题:

如果你的SQL语句写成了这样:

  1. 1、select * from table where ... order ...  
  2. 则优化后的sql以id排序  
  3.  
  4. 2、select *|CustomerId from table where ... order ...  
  5. 则优化后的sql以CustomerId排序  
  6.  
  7. 2、select CustomerId,CustomerName,... from table where ... order ...  
  8. 则优化后的sql以CustomerId排序   
  9. ==================================  


然后根据当前信息格式化分页显示的htmls,例如,页数、页号、总记录数、以及上下页按钮是否可用。具体代码:

  1. Code  
  2.    public static string AnalyticsPagingHtmls(string tableAndindex,int count, int size, int index)  
  3.     {  
  4.         string _GetPageHtml = GetPageHtml();  
  5.         return string.Format  
  6.             (  
  7.             _GetPageHtml.Substring(0, _GetPageHtml.IndexOf(",{4}];") + 6),  
  8.             count == 0 || count <= size ? "none" : "",  
  9.             index == 0 ? "0" : "1",  
  10.             index == 0 ? "0" : "1",  
  11.             (index + 1 == ((count % size) == 0 ? count / size : ((count / size) + 1))) ? "0" : "1",  
  12.             (index + 1 == ((count % size) == 0 ? count / size : ((count / size) + 1))) ? "0" : "1",  
  13.             size,  
  14.             index + 1,  
  15.             (count % size) == 0 ? count / size : (count / size) + 1,  
  16.             count,  
  17.             count == 0 ? "none" : "",  
  18.             tableAndindex,  
  19.             ((count % size) == 0 ? count / size : ((count / size) + 1))-1  
  20.             )  
  21.             + _GetPageHtml.Substring(_GetPageHtml.IndexOf(",{4}];") + 6);  
  22.     } 

 如何使用这个分页方法:

第一步:在配置文件里写下如下代码:

  1. Code  
  2.   <configSections> 
  3.     <section name="MyPaging" type="System.Configuration.NameValueSectionHandler"/> 
  4.   </configSections> 
  5.   <MyPaging> 
  6.   <add key="Paging" value="~/Paging/template.htm"/> 
  7.   </MyPaging> 

 第二步:在cs文件里,直接调用就行

  1. protected void Page_Load(object sender, EventArgs e)  
  2.     {  
  3.         if(MyPaging.IsPaging)  
  4.         {  
  5.             p1.InnerHtml = MyPaging.ExecutePaging(MyRep, "select CustomerId,ShipName,ShipAddress,ShippedDate from orders ", 0,5);  
  6.             p2.InnerHtml = MyPaging.ExecutePaging(MyRep2, "select CustomerID,CompanyName,ContactName,Address from dbo.Customers", 0,5);  
  7.         }  
  8.     } 


前台代码:

  1. Code  
  2. <%@ Page Language="C#"   AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %> 
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
  4. <html xmlns="http://www.w3.org/1999/xhtml"> 
  5. <head runat="server"> 
  6.     <title></title> 
  7. </head> 
  8. <body> 
  9.     <form id="form1" runat="server"> 
  10.     <asp:Repeater ID="MyRep" runat=server> 
  11.     <ItemTemplate> 
  12.     <div style="width:100%; height:20px;"> 
  13.     <%# Eval("CustomerID") %> 
  14.     <%# Eval("ShipName") %> 
  15.     <%# Eval("ShipAddress") %> 
  16.     <%# Eval("ShippedDate")%> 
  17.     </div> 
  18.     </ItemTemplate> 
  19.     </asp:Repeater> 
  20.     <div id="p1" runat=server></div> 
  21.       
  22.     <asp:Repeater  ID="MyRep2" runat=server> 
  23.     <ItemTemplate> 
  24.     <div style="width:100%; height:20px;"> 
  25.     <%# Eval("CustomerID")%> 
  26.     <%# Eval("CompanyName")%> 
  27.     <%# Eval("ContactName")%> 
  28.     <%# Eval("Address")%> 
  29.     </div> 
  30.     </ItemTemplate> 
  31.     </asp:Repeater> 
  32.     <div id="p2" runat=server></div> 
  33.     </form> 
  34. </body> 
  35. </html> 

实现效果:

效果图 

原文标题:asp.net简单&高效的分页实现,请大家提提意见

链接:http://www.cnblogs.com/chenxumi/archive/2009/11/05/1596777.html

 

责任编辑:彭凡 来源: 博客园
相关推荐

2012-04-23 15:10:18

ASP.NET

2009-07-28 14:47:18

ASP.NET MVC

2009-08-04 10:02:36

中国站长站

2009-07-28 10:01:16

ASP.NET Exc

2009-09-10 09:50:47

ASP.NET MVC

2009-07-22 16:02:39

ASP.NET MVCPagedList

2009-07-27 15:34:11

MembershipASP.NET

2009-07-24 13:41:15

ASP.NET AJA

2009-08-05 18:36:12

ASP.NET Che

2009-07-23 10:37:43

2009-07-24 10:53:51

ASP.NET实现静态

2009-08-05 16:59:55

ASP.NET组件设计

2009-07-27 10:18:12

TypeResolveASP.NET

2009-07-22 18:03:00

ASP.NET ASP

2009-07-31 12:43:59

ASP.NET MVC

2009-08-05 15:50:13

ASP.NET优点

2009-08-04 14:23:36

ASP.NET查询分页

2009-08-10 13:32:15

ASP.NET TimASP.NET组件设计

2009-07-29 14:12:45

ASP.NET tra

2009-08-03 13:38:18

ASP.NET编程模型
点赞
收藏

51CTO技术栈公众号