ASP.NET MVC2.0在Tab頁中實現非同步無重新整理分頁

來源:互聯網
上載者:User

概述

    很多地方都存在以Tab頁來呈現資料的方式,比如網易、新浪、搜狐、QQ等知名的門戶網站的首頁,還有大家熟知的部落格園首頁,都是用了tab頁來顯示資料。大家之所以喜歡用Tab,因為它能大大的增加顯示資料的空間,能在固定的空間中顯示更多的資料。分頁也是為了方便資料的顯示,在應用系統中必不可少。這篇文章使用Jquery在ASP.NET MVC中使用Tab頁,以及在Tab頁中實現非同步無重新整理的分頁功能。估計這個大家都會用得到的。

    在ASP.NET MVC中實現分頁,在之前的一篇博文:ASP.NET MVC2右鍵菜單和簡單分頁中已經實現了。實現的方式很簡單,在table下面加上一段<a/><a/><a/>...的html就行了。

    先介紹一個Jquery外掛程式:Tab,可以到http://jqueryui.com/download上下載。看下它內建一個例子的:

    看下本文的成果:

    一

實現:

按照它的Demo,在ASP.net mvc項目中引入js和css,以及Jquery。我在ASP.net MVC的母板頁中引入這些檔案:

    <link href="http://www.cnblogs.com/Content/base/ui.all.css" rel="stylesheet" type="text/css" />    <script src="http://www.cnblogs.com/Scripts/jquery-1.4.1.js" type="text/javascript"></script>    <script src="http://www.cnblogs.com/Scripts/ui.core.js" type="text/javascript"></script>    <script src="http://www.cnblogs.com/Scripts/ui.tabs.js" type="text/javascript"></script>

    引入之後,參考它的Demo在MVC項目中View中使用Tab。 可以看到比tab內建的demo多來了一個getContentTab函數。他有兩個參數,用於表示你要顯示

哪個tab頁的第幾頁資料。這裡預設載入的時候,顯示tabs-Shoes的第一頁資料。

   <script type="text/javascript">       $(document).ready(function () {           $("#tabs").tabs();           getContentTab('Shoes', 1);       });     </script>     <div id="tabs">        <ul>                  <li><a href="#tabs-Shoes" onclick="getContentTab('Shoes',1);">Shoes</a></li>            <li><a href="#tabs-Electronics" onclick="getContentTab('Electronics',1);">Electronics</a></li>            <li><a href="#tabs-Food" onclick="getContentTab('Food',1);">Food</a></li>        </ul>        <div id="tabs-Shoes">                    </div>        <div id="tabs-Electronics">                    </div>        <div id="tabs-Food">                    </div>    </div> 

當然在定義View之前要先寫好控制器的代碼,很簡單,基本上沒有代碼:

public ActionResult ViewCategory(){    return View();} 

好了,下面開始我們重要的幾步。顯示table以及實現table的分頁。這個demo的tab定義了三個tab頁,每一頁的table結構是一樣的,所以我定義一個使用者控制項來實現table和分頁。代碼如下:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MvcAjaxPaging.Models.ProductViewModel>" %><%@ Import Namespace="MvcAjaxPaging.HtmlHelpers"%>     <table class="grid">        <thead>            <tr>                <th>Product name</th>                <th>Category</th>            </tr>        </thead>        <tbody>            <% foreach (var product in ViewData.Model.Products) { %>                <tr>                    <td><%= product.Name %></td>                    <td><%= product.Category %></td>                </tr>            <% } %>        </tbody>    </table>        <div class="pager">        <%= Html.Pager(ViewData.Model.PagingInfo.CurrentPage, ViewData.Model.PagingInfo.ItemsPerPage, ViewData.Model.PagingInfo.TotalItems, "", ViewData["CategoryDisplayName"] as string)%>    </div>

我們再通過一個ajax調用來將這個控制項顯示在ViewCategory對應的View上,定義一個js函數:

function getContentTab(categoryName, page) {    var url = '<%= Url.Content("~/MyPaging/ViewByCategory/") %>' + categoryName + "/"  + page;    var targetDiv = "#tabs-" + categoryName;    $.get(url, null, function (result) {        $(targetDiv).html(result);    });}

我們看上面代碼,我們去請求服務端的ViewByCategory方法,擷取table中的資料。看ViewByCategory的代碼:

public ActionResult ViewByCategory(string categoryName, int? page){    categoryName = categoryName ?? this.categories[0];    int currentPageIndex = page.HasValue ? page.Value : 0;    ProductViewModel productViewModel = new ProductViewModel();        IList<Product> productsByCategory = this.allProducts.Where(p => p.Category.Equals(categoryName)).ToList();    productViewModel.Products = productsByCategory.Skip((currentPageIndex - 1) * 10).Take(10).ToList();    productViewModel.PagingInfo.CurrentPage = currentPageIndex;    productViewModel.PagingInfo.ItemsPerPage = 10;    productViewModel.PagingInfo.TotalItems = productsByCategory.Count;    return View("ViewByCategoryTable", productViewModel);}

為了簡單起見資料來來自記憶體,使用list的take來實現分頁。你可以很方便的改成從DB擷取資料。在看下如何產生分頁的html,其實很簡單,我們只要在產生的分頁的HTML中使用getContentTab函數就行了。

public static string Pager(this HtmlHelper helper, int currentPage, int currentPageSize, int totalRecords,string urlPrefix,string status){    StringBuilder sb1 = new StringBuilder();    int seed = currentPage % currentPageSize == 0 ? currentPage : currentPage - (currentPage % currentPageSize);    if (currentPage > 0)        sb1.AppendLine(String.Format("<a href='#' onclick=getContentTab(\"{0}\",\"{1}\") >Previous</a>", status, currentPage));    if (currentPage - currentPageSize >= 0)        sb1.AppendLine(String.Format("<a href='#' onclick=getContentTab(\"{0}\",\"{1}\") >...</a>", status, (currentPage - currentPageSize) + 1));    for (int i = seed; i < Math.Round((totalRecords / currentPageSize) + 0.5) && i < seed + currentPageSize; i++)    {        sb1.AppendLine(String.Format("<a href='#' onclick=getContentTab(\"{0}\",\"{1}\") >{1}</a>", status, i + 1));    }    if (currentPage + currentPageSize <= (Math.Round((totalRecords / currentPageSize) + 0.5) - 1))        sb1.AppendLine(String.Format("<a href='#' onclick=getContentTab(\"{0}\",\"{1}\") >...</a>", status, (currentPage + currentPageSize) + 1));    if (currentPage < (Math.Round((totalRecords / currentPageSize) + 0.5) - 1))        sb1.AppendLine(String.Format("<a href='#'  onclick=getContentTab(\"{0}\",\"{1}\") >Next</a>", status, currentPage + 2));    return sb1.ToString();}

效果:

二:

圖三:

總結:在asp.net mvc中實現了在tab頁中的非同步無重新整理分頁。這東西太常用了,放在這裡,希望對你有所協助。

代碼:http://cid-aef1e64945224a20.office.live.com/self.aspx/.Public/MvcAjaxPaging.rar

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.