I need to know how to get additional properties added to the object returned by PagedList.Mvc package when I use ToPagedList
so that I can avoid using ViewBags to pass sort order parameters around.
I know that when using ToPagedList
it converts an IEnumerable into an IPagedList and I've made my view Strongly Typed to PagedList.IPagedList<MyModel>
which allows me to get paging and use a foreach
to display the results in a table. However there doesn't seem to be any way for me to pass along additional values such as my sort order or filter string.
I'm using AutoMapper to map between my domain and ViewModel like this to flatten my domain model into a ViewModel:
Mapper.CreateMap<ToDo, IndexToDoViewModel>()
.ForMember(dest => dest.Priority,
opt => opt.MapFrom(src => src.Priority.PriorityName))
.ForMember(dest => dest.Staff,
opt => opt.MapFrom(src => src.Staff.StaffName));
so that to return data in my controller I can do
var query = Session.QueryOver<ToDo>();
var result = query.Fetch(p=>p.Priority).Eager
.Fetch(s=>s.Staff).Eager
.List();
var viewModel = AutoMapper.Mapper.Map<IEnumerable<ToDo>,
IEnumerable<IndexToDoViewModel>>(result)
.ToPagedList(pageNumber, PageSize);
return View(viewModel);
So that in my View I can strongly type it like this
@model PagedList.IPagedList<TheWorkshop.Web.Models.Read.IndexToDoViewModel>
Which in turn allows me to get the paging I want with a nice simple
@Html.PagedListPager(@Model, page => Url.Action("Index", new { page = page}))
and to display my list of Todo Items use a
@foreach (var item in Model) { ....
to iterate through them
As I said the trouble is that I also want to have properties such as the SortOrder
, SearchFilter
and IncludeCompleted
in my ViewModel because at present they're being passed around in ViewBags and I'd like to clean that up.
@Html.ActionLink("Name", "Index", new {sortOrder=ViewBag.NameSortParam,
includeComplete = ViewBag.IncludeCompleted})
But because they're not part of the ToDo entity, they really belong on the ToPagedList extensions I'm stuck. Ideally I'd like to somehow pass them along with the other properties that are exposed by being a PagedList such as PageCount
or PageNumber
, but short of deriving my own PagedList or forking the original I don't see how I can support passing such properties. All the examples on the github page make heavy use of ViewBag.
I've been unable to add a wrapper class around my IndexToDoViewModel
so it has an IEnumerable or IPagedList as well as the sorting properties as this then makes my AutoMappings invalid.
Am I stuck with using ViewBags for the SortOrder filter or is there a way to have my cake and eat it by getting the properties included in my ViewModel, using AutoMapper and keeping the view strongly typed?