C# – The model item passed into the dictionary is of type ”, but this dictionary requires a model item of type ”

asp.net-mvcasp.net-mvc-3crazor

I am trying to get into the mvc technology and I am reading a book 'pro asp.net mvc 3 framework' from apress.
I got stuck at one place and I don't know how to solve it now, since this is so much different then ordinary web forms.
Here is the error I am getting: The model item passed into the dictionary is of type 'System.Data.Entity.Infrastructure.DbQuery`1[SportsStore.Domain.Entities.Product]', but this dictionary requires a model item of type 'SportsStore.WebUI.Models.ProductsListViewModel'.

I don't know which code exactly I need to paste but this is what I have:

View:

@model SportsStore.WebUI.Models.ProductsListViewModel           
@{
    ViewBag.Title = "Products";
}

<h2>List</h2>

@foreach (var s in Model.Products)
{
    <div class="item">
    <h3>@s.Name</h3>
    @s.Description
    <h4>@s.Price.ToString("c")</h4>
    </div>    
}

<div class="pager">
@Html.PageLinks(Model.PagingInfo, x => Url.Action("List", new { page = x }));
</div>

product controller:

namespace SportsStore.WebUI.Controllers
{
    public class ProductController : Controller
    {
        public int PageSize = 4;
        private IProductsRepository repository;

        public ProductController(IProductsRepository productsRepository)
        {
            repository = productsRepository;
        }

        public ViewResult List(int page=1)
        {
            ProductsListViewModel viewModel = new ProductsListViewModel
            {
                Products = repository.Products
                .OrderBy(p => p.ProductID)
                .Skip((page - 1) * PageSize)
                .Take(PageSize),
                PagingInfo = new PagingInfo
                {
                    CurrentPage = page,
                    ItemsPerPage = PageSize,
                    TotalItems = repository.Products.Count()
                }
            };
            return View(repository.Products.OrderBy(p => p.ProductID).Skip((page - 1) * PageSize).Take(PageSize));
        }       
    }    
}

Please let me know if you need more info.
Thanks, Laziale

Best Answer

Change this:

return View(repository.Products.OrderBy(p => p.ProductID).Skip((page - 1) * PageSize).Take(PageSize));

to this:

return View(viewModel);

Your page is expecting a model of type SportsStore.WebUI.Models.ProductsListViewModel. You were creating an instance of this view model from your data repository, but didn't do anything with it once it was created. MVC was getting confused because the model that you sent to the view was different than it was expecting. I just change the return to use the viewModel that you had already created in the lines before the return.