ASP.NET MVC 中的資料分頁(二)

來源:互聯網
上載者:User

在網頁上進行表格資料或其他顯示資料的分頁是一種十分常見的需求,以前我們有 GridView 或 DataPager 可以幫我們自動分頁,雖然到了 ASP.NET MVC 一切全部重頭來過,但我們也不用真的那麼辛苦的自己實做分頁,因為早就有人幫我們寫好程式並開放原始碼分享給這個世界了。如果你已經體會到在 ASP.NET MVC 中妥善利用強型別(Strong Typed)特性進行開發的優點時,你將會發現搭配 Visual Studio 2008 進行專案開發的過程有多美妙。以下我先舉一個簡單的例子:你 可以在 Controller 中定義一個 Action 方法,並在裡面先取得所有需顯示在 View 中的資料,如果你用 LINQ to SQL 的話,可以直接傳入 IQueryable 型別的物件到 View 中,當成 View 裡面使用的 Model,這樣可以享受延遲載入(Defered Loading) 的效果。

view plaincopy to clipboardprint?
  1. public ActionResult Index()  
  2. {  
  3.     IQueryable<Customer> custs =     
  4.         from cust in db.Customers     
  5.         where cust.City == "Taiwan"  
  6.         select cust;   
  7.           
  8.     return View(custs);  
  9. }  

之後在你的 View 中宣告繼承時可透過泛型指派 IQueryable<Customer> 進去:

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

或是轉型成統一個 IEnumable<Customer> ,這也是比較常見的用法:

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

然後你就可以利用 foreach 取出所有資料並將資料顯示出來了:

view plaincopy to clipboardprint?
  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>  

這就是標準的 ASP.NET MVC 取得資料並顯示在 View 中的 Pattern。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.