n 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.Roun
|