溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

asp.net學(xué)習(xí)筆記之分頁設(shè)計(jì)介紹

發(fā)布時間:2020-05-11 10:46:03 來源:億速云 閱讀:235 作者:Leah 欄目:編程語言

asp.net的分頁設(shè)計(jì)是什么?怎么使用?針對這幾個問題,今天小編總結(jié)這篇分頁設(shè)計(jì)的文章,希望幫助更多想學(xué)習(xí)分頁設(shè)計(jì)的同學(xué)找到更加簡單易行的辦法。

    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:              //分頁實(shí)現(xiàn)
    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:              //分頁數(shù)據(jù)讀取
    23:              newsBLL bll = new newsBLL();
    24:              DataTable dt = bll.ListByPaginationForView("Time", pager.PageSize, pager.CurrentPageIndex, "1", strCondition);
    25:
    26:              //獲取總頁數(shù)
    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"><h5>新聞列表</h5><span>當(dāng)前位置:<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:
這樣仍然有一些問題:
    為什么一定要后臺處理呢?
    為什么后臺要做這些顯示相關(guān)的?
    后臺只負(fù)責(zé)提供數(shù)據(jù),而界面實(shí)現(xiàn),完全應(yīng)該由js解決&hellip;&hellip;
    因此,就有了現(xiàn)在這個版本&hellip;
    上網(wǎng)研究了一下Jquery pager,然后在他的基礎(chǔ)上,該改改,然后就有了現(xiàn)在這個版本,后臺只負(fù)責(zé)提供數(shù)據(jù)(json格式)
    前臺負(fù)責(zé)界面顯示
    js分頁:
    1:  //Download by

    2:  //每次只顯示5個頁碼
    3:  //修改:2012/4/26
    4:  //tianzhuanghu
    5:  //http://www.cnblogs.com/mysweet/ 我的博客
    6:  (function($) {
    7:      //設(shè)定頁碼方法,初始化
    8:      $.fn.setPager = function(options) {
    9:          var opts = $.extend({}, pagerDefaults, options);
    10:          return this.each(function() {
    11:          //修改,能夠動態(tài)設(shè)置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:      //設(shè)定頁數(shù)及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:              //頁碼部分隱藏 只顯示中間區(qū)域
    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>&hellip;</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>&hellip;</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>&hellip;</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>&hellip;</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="大師風(fēng)采" %>
    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:              //頁面數(shù)據(jù)填充
    21:         $("#tBodyMaster")。empty();
    22:         $.each(Data,function(key,value){
    23:            //圖片回調(diào)(集中請求)
    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:              <h4>
    55:                  大師風(fēng)采</h4>
    56:              <span><a href="/Default.aspx">首頁</a> > 大師風(fēng)采</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:                              大師個人網(wǎng)頁
    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>
后臺則負(fù)責(zé)數(shù)據(jù)的提供:
    1:    /// <summary>
    2:      /// 搜索調(diào)用
    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:          //對搜索內(nèi)容進(jìn)行驗(yàn)證
    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:          //分頁數(shù)據(jù)讀取
    25:          IEnumerable<master> list = bll.ListByPagination(sortField, pageSize, pageIndex + 1, sortOrder == "asc" ? "1" : "0", strCondition);
    26:          //獲取總頁數(shù)
    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數(shù)據(jù)(List->json)
    3:          /// </summary>
    4:          /// <typeparam name="T">泛型</typeparam>
    5:          /// <param name="list">實(shí)現(xiàn)了Ilist接口的list</param>
    6:          /// <param name="total">記錄總數(shù)</param>
    7:          /// <param name="paramMaxMin">這里放排序的參數(shù)例如,string para=""maxAge":37,"avgAge":27,"minAge":24"</param>
    8:          /// <returns>返回json數(shù)據(jù)</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:          }
存儲過程:一直就用的上網(wǎng)找的,一個非常完美的存儲過程:(感覺優(yōu)化的很好,我做了多次封裝,用起來非常方便):
    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, -- 返回記錄總數(shù), 非0 值則返回
    17:       @OrderType bit = 0, -- 設(shè)置排序類型, 非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,就執(zhí)行總數(shù)統(tǒng)計(jì)。以下的所有代碼都是@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,就執(zhí)行降序,這句很重要!
    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:                           --如果是第一頁就執(zhí)行以上代碼,這樣會加快執(zhí)行速度
    55:                   end
    56:               else
    57:                   begin
    58:                       --以下代碼賦予了@strSQL以真正執(zhí)行的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)
關(guān)于asp.net中的分頁設(shè)計(jì)介紹就分享到這里了,希望以上內(nèi)容可以對大家有一定的參考價值,可以學(xué)以致用。如果喜歡本篇文章,不妨把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI