I am trying to convert to using ViewModels in my mvc4 application. I have successfully switched my POST actions to use viewmodels, but in the below example, I am trying to use both automapper and PagedList in an action.
I have made a class called AutoMapperConfiguration (below) to avoid adding mapping throughout the application:
public class AutoMapperConfiguration
{
public static void Configure()
{
ConfigureItemMapping();
}
public class PagedListConverter : ITypeConverter<PagedList<Item>,PagedList<ItemListViewModel>>
{
public PagedList<ItemListViewModel> Convert(ResolutionContext context)
{
var model = (PagedList<Item>)context.SourceValue;
var vm = model.Select(m => Mapper.Map<Item, ItemListViewModel>(m)).ToPagedList(model.PageNumber,model.PageSize);
return new PagedList<ItemListViewModel>(vm,model.PageNumber,model.PageSize);
}
}
private static void ConfigureItemMapping()
{
Mapper.CreateMap<ItemListViewModel,Item>();
Mapper.CreateMap<PagedList<Item>, PagedList<ItemListViewModel>>()
.ConvertUsing<PagedListConverter>();
}
}
The above is called from Global.asax
protected void Application_Start()
{
...
AutoMapperConfiguration.Configure();
...
}
From the controller, I am trying to send a list of items to the itemViewModel from the item Model as a Paged List. This is where I have become completely stuck. Needless to say the below doesn't work.
[HttpGet]
public ActionResult Index(int page = 1)
{
//Show 10 items per page for the Admin
int pageSize = 10;
var items = new PagedList<Item>(
db.Items.OrderBy(i => i.ItemId),page,pageSize);
var vm = new ItemListViewModel();
Mapper.Map<PagedList<Item>, PagedList<ItemListViewModel>>(items);
return View(vm);
}
Error now being seen is:
Missing type map configuration or unsupported mapping.
Mapping types: Item -> ItemListViewModel Project.Models.Item -> Project.ViewModels.ItemListViewModel
Destination path: ItemListViewModel
It is being thrown on the following line in the PagedListConverter
var vm = model.Select(m => Mapper.Map<Item, ItemListViewModel>(m)).ToPagedList(model.PageNumber,model.PageSize);
Any help would be appreciated.
I would create a
PagedList<Item>
manually and then map to aPagedList<ItemViewModel>
:Then it also seems like your converter needs some tweaks too. It should probably take the page number and size from the source
PagedList
:Also make sure to use your custom converter when you call
CreateMap
:You also need a map from
Item
toItemViewModel
: