ASP.NET MVC 中的数据分页(三

我們最近在開發 ASP.NET MVC 專案的過程中,除了自行研究如何有效分頁以外,也上網找了好幾套 ASP.NET MVC 分頁的解決方案,最後我們總結出一個最好用的就是這個元件 ( Paging with ASP.NET MVC )。

要利用這個元件進行資料分頁,不外乎有幾件事必須做到:

  1. 需傳入一個 page 參數到 Action 中,用以指定你目前要顯示「第幾頁」的資料。
  2. 準備傳入的資料(Model),可透過 Paging with ASP.NET MVC 元件中提供的 Extension Method 將 IList<T>, IQueryable<T>, 或 IEnumable<T> 型別的資料轉換成 IPagedList<T> 的型別,並傳入 View 中。
  3. 透過一個自訂的 Html Helper 在 View 中必須顯示「分頁導覽列」的資訊 (如下圖) 
    分頁導覽列

依據上面三個步驟進行修改,Action 的程式碼會變成這樣:

  1. // 分頁後每頁顯示的筆數  
  2. int defaultPageSize = 10;  
  3.   
  4. // 傳入 page 參數 ( 透過 Model Binder 綁進來的 )  
  5. public ActionResult Index(int? page)  
  6. {  
  7.     IQueryable<Customer> custs =     
  8.         from cust in db.Customers     
  9.         where cust.City == "Taiwan"  
  10.         select cust;   
  11.       
  12.     // 計算出目前要顯示第幾頁的資料 ( 因為 page 為 Nullable<int> 型別 )  
  13.     int currentPageIndex = page.HasValue ? page.Value - 1 : 0;  
  14.   
  15.     // 透過 ToPagedList 這個 Extension Method 將原本的資料轉成 IPagedList<T>  
  16.     return View(custs.ToPagedList(currentPageIndex, defaultPageSize));  
  17. }  

然後在 View 中顯示資料的地方,透過一個自訂的 Html Helper 方法顯示分頁資訊。

首先必須先修改傳入 View 的 Model 型別

  1. <%@ Page Language="C#"   
  2.          Inherits="System.Web.Mvc.ViewPage<IPagedList<Customer>>" %>  

然後再宣告匯入 MvcPaging 命名空間,好讓 Html.Pager 這個 Html Helper Method 可以使用: 
備註: 也可以在 web.config 設定,請參考 ASP.NET 如何預設匯入指定的命名空間(Namespace) 文章!

  1. <%@ Import Namespace="MvcPaging"%>  

然後原本顯示資料的程式「完全不用改寫」,只要加上「分頁導覽列」即可:

  1. <table>  
  2. <% foreach (var item in Model) { %>  
  3. <tr>  
  4.     <td><%= Html.Encode(item.ID) %></td>  
  5.     <td><%= Html.Encode(item.Name) %></td>  
  6.     <td><%= Html.Encode(item.Tel) %></td>  
  7. </tr>  
  8. <% } %>  
  9. </table>  
  10.   
  11. <div class="pager">  
  12. <%= Html.Pager(Model.PageSize, Model.PageNumber, Model.TotalItemCount) %>  
  13. </div>  

原文地址:https://www.cnblogs.com/ghfsusan/p/1455672.html