PagerHelper for ASP.NET MVC3 makes it easier for add pagination to your website.
First, implement IPagable in any viewmodel that you have in your project that you want to enhance with Pagination functionality.
namespace ar.com.juanpabloibanez.Samples.ViewModels { public class SearchProducViewModel : IPageble { public SearchProducViewModel() { PagerViewModel = new PagerViewModel(); } public PagerViewModel PagerViewModel { get; set; } public IEnumerable<Product> ListOfProducts { get; set; } public bool Active { get; set; } public string Name { get; set; } public int Delete { get; set; } } }
Then use the @Html.Pager helper method in the view and pass to it an instance ofPagerViewModel class that you can obtain from your model.
@using ar.com.juanpabloibanez.MVC.PagerHelper.Helpers
@using ar.com.juanpabloibanez.Samples.ViewModels
@model SearchProducViewModel
<table>
<thead>
<tr>
<th>Name</th>
<th>Price</th>
<th>Active</th>
<th>Action</th>
</tr>
</thead>
<tbody>
@foreach (var product in Model.ListOfProducts)
{
<tr>
<td>@product.Name</td>
<td>@product.Price</td>
<td>@product.Active</td>
<td><button name="Delete" value="@product.Id" type="submit" class="deleteButton">Delete</button></td>
</tr>
}
</tbody>
</table>
@Html.Pager(Model.PagerViewModel)
Also you can use the Skip and Take properties fromPagerViewModel to help you in your controller. The only important thing that we have to do previous usingSkip and Take is to set TotalItems property.
public ActionResult Index(SearchProducViewModel searchProducViewModel) { ViewBag.EnhancePage = true; ViewBag.Action = "Index"; DoIndex(searchProducViewModel); if (Request.IsAjaxRequest()) { return PartialView("ProductsGrid", searchProducViewModel); } else { return View("Index",searchProducViewModel); } }
private void DoIndex(SearchProducViewModel searchProducViewModel) { if (searchProducViewModel.Delete > 0) { Product product = products.Where(x => x.Id == searchProducViewModel.Delete).Single(); products.Remove(product); } var filteredProducts = from p in products where p.Active == searchProducViewModel.Active && (searchProducViewModel.Name == null || p.Name.Contains(searchProducViewModel.Name)) select p; searchProducViewModel.PagerViewModel.TotalItems = filteredProducts.Count(); searchProducViewModel.ListOfProducts = filteredProducts .Skip(searchProducViewModel.PagerViewModel.Skip) .Take(searchProducViewModel.PagerViewModel.Take); }
Demo http://pagerhelper.apphb.com/
本文介绍了如何通过实现IPagable接口并利用PagerHelper方法,轻松为ASP.NET MVC3项目中的视图模型添加分页功能。具体步骤包括在视图模型中实现接口、在视图中调用分页助手方法,并在控制器中使用Skip和Take属性进行数据过滤和分页。演示了一个简单的应用实例和官方示例链接。

64

被折叠的 条评论
为什么被折叠?



