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/
http://pagerhelper.codeplex.com/