Howto use MvcContrib.Pagination with a ViewModel
I was looking for a simple solution for paging in a ASP.MVC2 project. Though we already use MVCContrib.Grid this was the first place I searched.
The solution MVCContrib offers is elegant in the way that they separated the concept of paging, a ui element to show paging (next , previous, …) and a grid to show the content. This separation allows us to using paging on a custom table based page as well.
Because we are using ViewModels a little extra effort was needed to retain the paging information from the domain layer in the view layer.
Step by step:
* Get a Querable from repository using Domain Objects
IQueryable<DomainObject> domainObjects = rep.GetAll()
* Filter and Sort using Linq
domainObjects = domainObjects.Where(...).OrderBy(...)
* Get the data
IPagination<DomainObject> pageOfData domainObjects.AsPagination( page, pageSize)
* Map to the ViewModel
IPagination<DomainObjectViewModel> model = DomainObjectViewModel.Map( pageOfData )
* Mapping needs to retain the page information from the domain
var list = new List<DomainObjectViewModel>();
foreach (var domainObject in domainObjects)
{
list.Add(Map(domainObject));
}
new CustomPagination<DomainObjectViewModel>(list.AsEnumerable(),
pageOfData.PageNumber,
pageOfData.PageSize,
pageOfData.TotalItems);
* Show the information on a page in a grid
<%= Html.Grid(Model).AutoGenerateColumns() %>
* Show the pager
<%= Html.Pager(Model).First( "<<").Last(">>").Next(">").Previous("<")
.Format( "Item {0} - {1} van {2} ") %>
