asp.net學習_分頁設計相關知識

分頁是每個程序員都天天都在打交道的東西,分頁。
   
    一年前,剛接觸的時候,根本不知道什麼叫作分頁,後臺,xxx說,若是數據過多一次,成千上萬條,你一次只看到10-20條,爲何要所有顯示呢?當時感受很震撼,爲何呢?
   
    如下內容是之前的代碼(不要扔雞蛋,我如今看了都有巴不得砸電腦的衝動)
    因而咱們就用了第一個分頁版本,當時,兩個實驗室的"戰士"研究了很久,找到一個存儲過程的分頁,當時感受好神奇!找找當時凌亂的分頁調用程序:
 javascript

如今看了都要砸電腦的衝動的東東.....
 
後來作web,凌亂依舊,web版本的分頁程序,css

後來才發現一個叫作aspnetpager的控件,發現好強大呀,易用,方便,並且不用寫那麼複雜的存儲過程以及調用,
慢慢的發現,這些控件都是死的,寫死的東西,根本沒有靈活性,特別是美工作個好看點的分頁之類的,只能乾瞪眼,要不就按照它的格式作分頁樣式,這是一個糾結的問題,
    既然不靈活,爲何不本身作控件?
    後來就本身寫分頁的用戶控件…
    不過仍然不夠靈活,上網找資料。
    發現,手寫一個分頁類就好了,分頁不就是計算頁面大小,而後輸出頁碼和鏈接麼?
    而後就是這個版本
    1:    //  //記錄日誌
    2:      private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod()。DeclaringType);
    3:      //輸出的PagerHtml代碼
    4:      public string PagerHtml = "";
    5:      protected void Page_Load(object sender, EventArgs e)
    6:      {
    7:          try
    8:          {
    9:              string TypeId = Request["TypeId"];
    10:              //查詢條件
    11:              string strCondition = "";
    12:              //字符串注入檢測
    13:              if (!string.IsNullOrEmpty(TypeId) && Tools.IsValidInput(ref TypeId, true))
    14:                  strCondition = "TypeId=" + TypeId;
    15:
    16:              //分頁實現
    17:              var pager = new Common.RupengPager();
    18:              pager.UrlFormat = "NewsList.aspx?pagenum={n}&TypeId=" + TypeId;
    19:              pager.PageSize = 30;
    20:              pager.TryParseCurrentPageIndex(Request["pagenum"]);
    21:
    22:              //分頁數據讀取
    23:              newsBLL bll = new newsBLL();
    24:              DataTable dt = bll.ListByPaginationForView("Time", pager.PageSize, pager.CurrentPageIndex, "1", strCondition);
    25:
    26:              //獲取總頁數
    27:              pager.TotalCount = bll.GetVNewsListCount(strCondition);
    28:              rpData.DataSource = dt;
    29:              rpData.DataBind();
    30:
    31:              //渲染頁碼條HTML
    32:              PagerHtml = pager.Render();
    33:          }
    34:          catch (Exception ex)
    35:          {
    36:              logger.Error("錯誤:", ex);
    37:          }
    38:      }
效果也就是這樣:
    前臺就是
    1:  <%@ Page Language="C#" MasterPageFile="~/InfoPage.master" AutoEventWireup="true" CodeFile="NewsList.aspx.cs" Inherits="News_NewsList" Title="新聞列表" %>
    2:
    3:  <asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
    4:      <link href="/css/other.css" rel="stylesheet" type="text/css" />
    5:      <link href="/css/Pager.css" rel="stylesheet" type="text/css" />
    6:  </asp:Content>
    7:  <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    8:      <%--GetNewsTypeInfoForNewsByJson--%>
    9:
    10:     <div class="list">
    11:          <div class="list_title"><h4>新聞列表</h4><span>當前位置:<a href="/Default.aspx">首頁</a> > 新聞列表</span></div>
    12:          <ul>
    13:              <asp:Repeater ID="rpData" runat="server">
    14:              <ItemTemplate>
    15:               <li><a href='ViewNews.aspx?NewsId=<%#Eval("Id") %>'>[<%#Eval("TypeName")%>]<%#Eval("Title")%></a><span><%#Eval("Time")%></span></li>
    16:              </ItemTemplate>
    17:              </asp:Repeater>
    18:          </ul>
    19:          <div class="page">
    20:                <p><div class="pager"><%=PagerHtml%></div></p>
    21:
    22:          </div>
    23:      </div>
    24:
    25:  </asp:Content>
    26:
這樣仍然有一些問題:
    爲何必定要後臺處理呢?
    爲何後臺要作這些顯示相關的?
    後臺只負責提供數據,而界面實現,徹底應該由js解決……
    所以,就有了如今這個版本…
    上網研究了一下Jquery pager,而後在他的基礎上,該改改,而後就有了如今這個版本,後臺只負責提供數據(json格式)
    前臺負責界面顯示
    js分頁:
    1:  //Download by html

    2:  //每次只顯示5個頁碼
    3:  //修改:2012/4/26
    4:  //tianzhuanghu
    5:  //http://www.cnblogs.com/mysweet/ 個人博客
    6:  (function($) {
    7:      //設定頁碼方法,初始化
    8:      $.fn.setPager = function(options) {
    9:          var opts = $.extend({}, pagerDefaults, options);
    10:          return this.each(function() {
    11:          //修改,可以動態設置PageSize
    12:              pagerDefaults.PageSize=options.PageSize;
    13:              $(this)。empty()。append(setPagerHtml(parseInt(options.RecordCount), parseInt(options.PageIndex), options.buttonClick));
    14:               $('.pager a')。mouseover(function() { document.body.style.cursor = "pointer"; })。mouseout(function() { document.body.style.cursor = "auto"; });
    15:          });
    16:      };
    17:      //設定頁數及html
    18:      function setPagerHtml(RecordCount, PageIndex, pagerClick) {
    19:
    20:          var $content = $("<div class=\"pager\"></div>");
    21:          var startPageIndex = 1;
    22:          //若頁碼超出
    23:          if (RecordCount <= 0) RecordCount = pagerDefaults.PageSize;
    24:          var    PageSize=pagerDefaults.PageSize;
    25:          //alert(pagerDefaults.PageSize);
    26:          //末頁
    27:          var endPageIndex = parseInt(RecordCount % parseInt(PageSize)) > 0 ? parseInt(RecordCount / parseInt(PageSize)) + 1 : RecordCount / parseInt(PageSize);
    28:
    29:          if (PageIndex > endPageIndex) PageIndex = endPageIndex;
    30:          if (PageIndex <= 0) PageIndex = startPageIndex;
    31:          var nextPageIndex = PageIndex + 1;
    32:          var prevPageIndex = PageIndex - 1;
    33:          if (PageIndex == startPageIndex) {
    34:              $content.append($("<span>首頁</span>"));
    35:              $content.append($("<span>上一頁</span>"));
    36:          } else {
    37:
    38:              $content.append(renderButton(RecordCount, 1, pagerClick, "首頁"));
    39:              $content.append(renderButton(RecordCount, prevPageIndex, pagerClick, "上一頁"));
    40:          }
    41:          //這裏判斷是否顯示頁碼
    42:          if (pagerDefaults.ShowPageNumber) {
    43:              // var html = "";
    44:              //頁碼部分隱藏 只顯示中間區域
    45:              if (endPageIndex <= 5 && PageIndex <= 5) {
    46:                  for (var i = 1; i <= endPageIndex; i++) {
    47:                      if (i == PageIndex) {
    48:                          $content.append($("<span>" + i + "</span>"));
    49:                      } else {
    50:                          $content.append(renderButton(RecordCount, i, pagerClick, i));
    51:                      }
    52:
    53:                  }
    54:
    55:              } else if (endPageIndex > 5 && endPageIndex - PageIndex <= 2) {
    56:
    57:                  $content.append($("<a>…</a>"));
    58:                  for (var i = endPageIndex - 4; i <= endPageIndex; i++) {
    59:                      if (i == PageIndex) {
    60:                          $content.append($("<span>" + i + "</span>"));
    61:                      } else {
    62:                          $content.append(renderButton(RecordCount, i, pagerClick, i));
    63:                      }
    64:
    65:                  }
    66:              } else if (endPageIndex > 5 && PageIndex > 3) {
    67:
    68:                  $content.append($("<a>…</a>"));
    69:                  for (var i = PageIndex - 2; i <= PageIndex + 2; i++) {
    70:                      if (i == PageIndex) {
    71:                         $content.append($("<span>" + i + "</span>"));
    72:                      } else {
    73:                          $content.append(renderButton(RecordCount, i, pagerClick, i));
    74:                      }
    75:
    76:                  }
    77:                 $content.append($("<a>…</a>"));
    78:
    79:              } else if (endPageIndex > 5 && PageIndex <= 3) {
    80:
    81:                  for (var i = 1; i <= 5; i++) {
    82:                      if (i == PageIndex) {
    83:                          $content.append($("<span>" + i + "</span>"));
    84:                      } else {
    85:                          $content.append(renderButton(RecordCount, i, pagerClick, i));
    86:                      }
    87:
    88:                  }
    89:                 $content.append($("<a>…</a>"));
    90:              }
    91:          }
    92:          if (PageIndex == endPageIndex) {
    93:              $content.append($("<span>下一頁</span>"));
    94:              $content.append($("<span>末頁</span>"));
    95:          } else {
    96:              $content.append(renderButton(RecordCount, nextPageIndex, pagerClick, "下一頁"));
    97:              $content.append(renderButton(RecordCount, endPageIndex, pagerClick, "末頁"));
    98:          }
    99:
    100:
    101:          return $content;
    102:      }
    103:      function renderButton(recordCount, goPageIndex, EventHander, text) {
    104:          var $goto = $("<a title=\"第" + goPageIndex + "頁\">" + text + "</a>\"");
    105:          $goto.click(function() {
    106:
    107:              EventHander(recordCount, goPageIndex,pagerDefaults.PageSize);
    108:          });
    109:          return $goto;
    110:      }
    111:      var pagerDefaults = {
    112:          DefaultPageCount: 1,
    113:          DefaultPageIndex: 1,
    114:          PageSize:20,
    115:          ShowPageNumber: true //是否顯示頁碼
    116:      };
    117:  })(jQuery);
    前臺頁面顯示:
    1:  <%@ Page Language="C#" MasterPageFile="~/InfoPage.master" AutoEventWireup="true"
    2:      CodeFile="MasterList.aspx.cs" Inherits="Master_MasterList" Title="大師風采" %>
    3:
    4:  <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
    5:      <link href="/css/other.css" rel="stylesheet" type="text/css" />
    6:
    7:      <script src="/Admin/scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
    8:
    9:      <script src="/js/jquery-pager-1.0.js" type="text/javascript"></script>
    10:
    11:      <link href="/css/pager.css" rel="stylesheet" type="text/css" />
    12:
    13:      <script type="text/javascript">
    14:          $(document)。ready(function() {
    15:              //加載PageSize和頁碼PageIndex
    16:              GetData(1,1);
    17:          });
    18:          function InitPager(RecordCount, PageIndex,PageSize,Data) {
    19:          $("#Pager")。setPager({ RecordCount: RecordCount, PageIndex: PageIndex,PageSize:PageSize, buttonClick: PageClick });
    20:              //頁面數據填充
    21:         $("#tBodyMaster")。empty();
    22:         $.each(Data,function(key,value){
    23:            //圖片回調(集中請求)
    24:           var PicSrc="/Admin/FileManage/GetImg.ashx?method=GetMasterPic&type=medium&fileName="+Data[key].Picturepath;
    25:              var item='<tr><td><a href="'+"#"+'"><img src="'+PicSrc+'" title="'+Data[key].Name+'" alt="'+Data[key].Name+'"/><br/>'+Data[key].Name+'</a></td>';
    26:              item+='<td class="jianjie"><span>'+Data[key].Introduction+'</span></td>';
    27:              item+='<td class="adress"><a href="'+"#"+'">'+Data[key].Name+'的主頁</a></td></tr>';
    28:         $("#tBodyMaster")。append(item);
    29:         });
    30:          };
    31:          PageClick = function(RecordCount,PageIndex,PageSize) {
    32:               GetData(PageSize,PageIndex);
    33:          };
    34:          //sortField排序字段
    35:         function GetData(PageSize,PageIndex){
    36:         $.ajax({
    37:         url:'/Admin/MasterManage/Data/MasterInfo.ashx?method=SearchMaster',
    38:         //注意後臺分頁存儲過程的PageIndex是從0開始的,因此這裏要-1
    39:         data:'sortField=Id&sortOrder=desc&pageIndex='+(PageIndex-1)+'&pageSize='+PageSize,
    40:         success:function(text){
    41:         var jsonData=$.parseJSON(text);
    42:         InitPager(jsonData.total, PageIndex,PageSize,jsonData.data);
    43:         }
    44:
    45:         });
    46:         }
    47:
    48:      </script>
    49:
    50:  </asp:Content>
    51:  <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    52:      <div class="list">
    53:          <div class="list_load">
    54:              <h3>
    55:                  大師風采</h3>
    56:              <span><a href="/Default.aspx">首頁</a> > 大師風采</span>
    57:          </div>
    58:          <div class="ol">
    59:              <table width="680" border="0" cellpadding="0" cellspacing="0">
    60:                  <thead>
    61:                      <tr>
    62:                          <th width="160">
    63:                              大師名稱
    64:                          </th>
    65:                          <th width="310">
    66:                              大師簡介
    67:                          </th>
    68:                          <th width="210">
    69:                              大師我的網頁
    70:                          </th>
    71:                      </tr>
    72:                  </thead>
    73:                  <tbody id="tBodyMaster">
    74:
    75:                  </tbody>
    76:              </table>
    77:          </div>
    78:          <div id="Pager">
    79:          </div>
    80:      </div>
    81:  </asp:Content>
後臺則負責數據的提供:
    1:    /// <summary>
    2:      /// 搜索調用
    3:      /// </summary>
    4:      /// <param name="context"></param>
    5:      public void SearchMaster(HttpContext context)
    6:      {
    7:          //查詢條件
    8:          string key = context.Request["key"];
    9:          //分頁
    10:          int pageIndex = Convert.ToInt32(context.Request["pageIndex"]);
    11:          int pageSize = Convert.ToInt32(context.Request["pageSize"]);
    12:          //字段排序
    13:          String sortField = context.Request["sortField"];
    14:          String sortOrder = context.Request["sortOrder"];
    15:          string strCondition = "";
    16:          //對搜索內容進行驗證
    17:          if (!Common.Tools.IsValidInput(ref key, false))
    18:          {
    19:              return;
    20:          }
    21:          else
    22:              strCondition = masterBLL.ConfirmCondition(key);//判斷查詢條件
    23:          masterBLL bll = new masterBLL();
    24:          //分頁數據讀取
    25:          IEnumerable<master> list = bll.ListByPagination(sortField, pageSize, pageIndex + 1, sortOrder == "asc" ? "1" : "0", strCondition);
    26:          //獲取總頁數
    27:          int totalPage = bll.GetCount(strCondition);
    28:          //JSON 序列化
    29:          string json = masterBLL.MiniUiListToJson(list, totalPage, "");
    30:
    31:
    32:          context.Response.Write(json);
    33:      }
    BLL生成json方法:(這個方法我是代碼生成器寫成一個模板,而後每次自動生成,省得每次都要寫,哈哈哈)
    1:      /// <summary>
    2:          /// 專門生成爲MiniUi生成json數據(List->json)
    3:          /// </summary>
    4:          /// <typeparam name="T">泛型</typeparam>
    5:          /// <param name="list">實現了Ilist接口的list</param>
    6:          /// <param name="total">記錄總數</param>
    7:          /// <param name="paramMaxMin">這裏放排序的參數例如,string para=""maxAge":37,"avgAge":27,"minAge":24"</param>
    8:          /// <returns>返回json數據</returns>
    9:          public static string MiniUiListToJson(IEnumerable<master> masterInfo, int total, string paramMaxMinAvg)
    10:          {
    11:              StringBuilder Json = new StringBuilder();
    12:              Json.Append("{\"total\":"+total+",\"data\":");
    13:              Json.Append("[");
    14:                  foreach (master Info in masterInfo)
    15:                  {
    16:                      Json.Append("{");
    17:                      Json.Append("\"Id\":\"" + Info.Id + "\"");
    18:                      Json.Append(",");
    19:                      Json.Append("\"Username\":\"" + Info.Username + "\"");
    20:                      Json.Append(",");
    21:                      Json.Append("\"Password\":\"" + Info.Password + "\"");
    22:                      Json.Append(",");
    23:                      Json.Append("\"Name\":\"" + Info.Name + "\"");
    24:                      Json.Append(",");
    25:                      Json.Append("\"Introduction\":\"" + Info.Introduction + "\"");
    26:                      Json.Append(",");
    27:                      Json.Append("\"Isrecommend\":\"" + Info.Isrecommend + "\"");
    28:                      Json.Append(",");
    29:                      Json.Append("\"Isshow\":\"" + Info.Isshow + "\"");
    30:                      Json.Append(",");
    31:                      Json.Append("\"Picturepath\":\"" + Info.Picturepath + "\"");
    32:                      Json.Append(",");
    33:                      Json.Append("\"Sex\":\"" + Info.Sex + "\"");
    34:                      Json.Append(",");
    35:                      Json.Append("\"Nation\":\"" + Info.Nation + "\"");
    36:                      Json.Append(",");
    37:                      Json.Append("\"mobilephone\":\"" + Info.mobilephone + "\"");
    38:                      Json.Append(",");
    39:                      Json.Append("\"Telephone\":\"" + Info.Telephone + "\"");
    40:                      Json.Append(",");
    41:                      Json.Append("\"Email\":\"" + Info.Email + "\"");
    42:                      Json.Append(",");
    43:                      Json.Append("\"QQ\":\"" + Info.QQ + "\"");
    44:                      Json.Append(",");
    45:                      Json.Append("\"Zipcode\":\"" + Info.Zipcode + "\"");
    46:                      Json.Append(",");
    47:                      Json.Append("\"Address\":\"" + Info.Address + "\"");
    48:                      Json.Append(",");
    49:                      Json.Append("\"appreciation\":\"" + Info.appreciation + "\"");
    50:                      Json.Append(",");
    51:                      Json.Append("\"website\":\"" + Info.website + "\"");
    52:                      Json.Append(",");
    53:                      Json.Append("\"Reward\":\"" + Info.Reward + "\"");
    54:                      Json.Append(",");
    55:                      Json.Append("\"BirthDay\":\"" + Info.BirthDay + "\"");
    56:                      Json.Append(",");
    57:                      Json.Append("\"state\":\"" + Info.state + "\"");
    58:                      Json.Append(",");
    59:                      Json.Append("\"state1\":\"" + Info.state1 + "\"");
    60:                      Json.Append(",");
    61:                      Json.Append("\"hit\":\"" + Info.hit + "\"");
    62:                      Json.Append(",");
    63:                      Json.Append("\"rank\":\"" + Info.rank + "\"");
    64:                      Json.Append("}");
    65:                      if(Info != masterInfo.Last())
    66:                      {
    67:                          Json.Append(",");
    68:                      }
    69:                  }
    70:              Json.Append("]}");
    71:              return Json.ToString();
    72:          }
存儲過程:一直就用的上網找的,一個很是完美的存儲過程:(感受優化的很好,我作了屢次封裝,用起來很是方便):
    1:  USE [czcraft]
    2:  GO
    3:  /****** 對象:  StoredProcedure [dbo].[pagination]    腳本日期: 04/26/2012 21:04:21 ******/
    4:  SET ANSI_NULLS ON
    5:  GO
    6:  SET QUOTED_IDENTIFIER ON
    7:  GO
    8:  CREATE PROCEDURE [dbo].[pagination]
    9:       @tblName varchar(255), -- 表名
    10:       @innerJohn varchar(500),  --inner john鏈接的表
    11:     --  @innerJohnCondition varchar(255),  --inner john鏈接條件
    12:       @strGetFields varchar(1000) = '*', -- 須要返回的列
    13:       @fldName varchar(255)='', -- 排序的字段名
    14:       @PageSize int = 10, -- 頁尺寸
    15:       @PageIndex int = 1, -- 頁碼
    16:       @doCount bit = 0, -- 返回記錄總數, 非0 值則返回
    17:       @OrderType bit = 0, -- 設置排序類型, 非0 值則降序
    18:       @strWhere varchar(1500) = '' -- 查詢條件(注意: 不要加where)
    19:  AS
    20:
    21:  declare @strSQL varchar(5000) -- 主語句
    22:  declare @strTmp varchar(110) -- 臨時變量
    23:  declare @strOrder varchar(400) -- 排序類型
    24:
    25:  if @doCount != 0
    26:       begin
    27:           if @strWhere !=''
    28:               set @strSQL = 'select count(*) as Total from [' + @tblName + '] '+@innerJohn +' where '+@strWhere
    29:           else
    30:               set @strSQL = 'select count(*) as Total from [' + @tblName + '] '+@innerJohn +' '
    31:       end
    32:       --以上代碼的意思是若是@doCount傳遞過來的不是0,就執行總數統計。如下的全部代碼都是@doCount爲0的狀況
    33:
    34:  else
    35:       begin
    36:           if @OrderType != 0
    37:               begin
    38:                   set @strTmp = '<(select min'
    39:                   set @strOrder = ' order by [' + @fldName +'] desc'
    40:                   --若是@OrderType不是0,就執行降序,這句很重要!
    41:               end
    42:
    43:           else
    44:               begin
    45:                   set @strTmp = '>(select max'
    46:                   set @strOrder = ' order by [' + @fldName +'] asc'
    47:               end
    48:               if @PageIndex = 1
    49:                   begin
    50:                       if @strWhere != ''
    51:                           set @strSQL = 'select top ' + str(@PageSize) +' '+@strGetFields+ ' from [' + @tblName + '] '+@innerJohn +' where ' + @strWhere + ' ' + @strOrder
    52:                       else
    53:                           set @strSQL = 'select top ' + str(@PageSize) +' '+@strGetFields+ ' from ['+ @tblName + '] '+@innerJohn + @strOrder
    54:                           --若是是第一頁就執行以上代碼,這樣會加快執行速度
    55:                   end
    56:               else
    57:                   begin
    58:                       --如下代碼賦予了@strSQL以真正執行的SQL代碼
    59:                       set @strSQL = 'select top ' + str(@PageSize) +' '+@strGetFields+ ' from '
    60:                           + @tblName + ' '+@innerJohn+ ' where [' + @fldName + ']' + @strTmp + '(['+ @fldName + ']) from (select top ' + str((@PageIndex-1)*@PageSize) + ' ['+ @fldName + '] from [' + @tblName + '] '+@innerJohn +' ' + @strOrder + ') as tblTmp)'+ @strOrder
    61:                           if @strWhere != ''
    62:                       set @strSQL = 'select top ' + str(@PageSize) +' '+@strGetFields+ ' from '
    63:                           + @tblName + ' '+@innerJohn+ ' where [' + @fldName + ']' + @strTmp + '(['
    64:                           + @fldName + ']) from (select top ' + str((@PageIndex-1)*@PageSize) + ' ['
    65:                           + @fldName + '] from [' + @tblName + '] '+@innerJohn +'  where ' + @strWhere + ' '
    66:                           + @strOrder + ') as tblTmp) and ' + @strWhere + ' ' + @strOrder
    67:       end
    68:  end
    69:
    70:  print(@PageIndex)
    71:
    72:  exec (@strSQL)
可能有人會問,爲何要作這麼多工做?
    但是試想一想,若是要把這些列表頁生成靜態頁面,那麼,這個頁面就很是容易生成了,這個ajax分頁更好更完美,
    若是用服務器控件,只要存在VIEWSTATE,生成靜態頁面就沒轍了。
    並且這麼設計結構清晰,更以維護,分離也更完全!
    一直在努力,從不曾放棄,努力學習中…… 歡迎一塊兒學習。net!
 java

相關文章
相關標籤/搜索