您的位置:首页 > 编程语言 > ASP

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

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

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

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



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

view plaincopy to clipboardprint?
// 分頁後每頁顯示的筆數
int defaultPageSize = 10;

// 傳入 page 參數 ( 透過 Model Binder 綁進來的 )
public ActionResult Index(int? page)
{
IQueryable<Customer> custs =
from cust in db.Customers
where cust.City == "Taiwan"
select cust;

// 計算出目前要顯示第幾頁的資料 ( 因為 page 為 Nullable<int> 型別 )
int currentPageIndex = page.HasValue ? page.Value - 1 : 0;

// 透過 ToPagedList 這個 Extension Method 將原本的資料轉成 IPagedList<T>
return View(custs.ToPagedList(currentPageIndex, defaultPageSize));
}

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

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

view plaincopy to clipboardprint?
<%@ Page Language="C#"
Inherits="System.Web.Mvc.ViewPage<IPagedList<Customer>>" %>

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

view plaincopy to clipboardprint?
<%@ Import Namespace="MvcPaging"%>

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

view plaincopy to clipboardprint?
<table>
<% foreach (var item in Model) { %>
<tr>
<td><%= Html.Encode(item.ID) %></td>
<td><%= Html.Encode(item.Name) %></td>
<td><%= Html.Encode(item.Tel) %></td>
</tr>
<% } %>
</table>

<div class="pager">
<%= Html.Pager(Model.PageSize, Model.PageNumber, Model.TotalItemCount) %>
</div>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: