I'm getting The model item passed into the dictionary error in visual studio 2015. The Error message says :The model item passed into the dictionary is of type 'System.Data.Entity.Infrastructure.DbQuery
1[CmsShoppingCart.Models.Data.ProductDTO]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[CmsShoppingCart.Models.ViewModels.Shop.ProductVM]'.
and in visual studio I'm getting "UNREACHABLE CODE DETECTED" at return View(productVMList); What I want to achieve is that to view the list of products and working search bar for products. My controller is
public ActionResult Category(string name,string searchString)
{
// Declare a list of ProductVM
List<ProductVM> productVMList;
using (Db db = new Db())
{
// Get category id
CategoryDTO categoryDTO = db.Categories.Where(x => x.Slug == name).FirstOrDefault();
int catId = categoryDTO.Id;
// Init the list
productVMList = db.Products.ToArray().Where(x => x.CategoryId == catId).Select(x => new ProductVM(x)).ToList();
// Get category name
var productCat = db.Products.Where(x => x.CategoryId == catId).FirstOrDefault();
ViewBag.CategoryName = productCat.CategoryName;
}
var product = from c in db.Products
select c;
if (!string.IsNullOrEmpty(searchString))
{
product = product.Where(c => c.Name == searchString);
}
return View(product);
// Return view with list
return View(productVMList);
}
And View is
@model IEnumerable<CmsShoppingCart.Models.ViewModels.Shop.ProductVM>
@{
ViewBag.Title = ViewBag.CategoryName;
}
<h2>@ViewBag.CategoryName</h2>
@using (Html.BeginForm("Index", "Shop", FormMethod.Post))
{
<div>
Search By Products @Html.TextBox("searchString")
<input id="Submit1" type="submit" value="Filter" />
</div>
}
<table class="table">
<tr>
<th>
Name
</th>
<th>
Description
</th>
<th>
Price
</th>
<th>
Image
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Description)
</td>
<td>
@Html.ActionLink("Price", "Category", new { SortOrder = ViewBag.Price })
$@Html.DisplayFor(modelItem => item.Price, new { SortOrder = ViewBag.Price })
</td>
<td>
<a href="/shop/product-details/@item.Slug">
<img src="/Images/Uploads/Products/@item.Id/Thumbs/@item.ImageName" />
</a>
</td>
<td>
<a href="/shop/product-details/@item.Slug">Details</a>
</td>
</tr>
}
</table>