Reputation: 101
I am new to Ninjet and Mvc. I know that error mean I am passing the wrong type to the view. but I can't figure out where is the error. here are my classes
public class ProdListViewModel
{
public ProdListViewModel()
{
this.ProductsList = new List<ProdViewModel>();
}
public ProdListViewModel(List<product> products)
{
this.ProductsList = new List<ProdViewModel>();
foreach (var prod in products)
{
this.ProductsList.Add(new ProdViewModel(prod));
}
}
public List<ProdViewModel> ProductsList { get; set; }
}
public class ProdViewModel
{
[Key]
public int productsID { get; set; }
[Required]
[StringLength(50)]
public string pname { get; set; }
public ProdViewModel()
{
}
public ProdViewModel(product product)
{
productsID = product.productsID;
pname = product.pname;
}
}
this is my control. as you can see I am using ninjet. I check I am returning to product a list of 2 product. but
public class ProductController : ControllerBase
{
internal readonly IProductRepository productRepository;
public ProductController(IProductRepository productRepository)
{
this.productRepository = productRepository;
}
// GET: Product
public ActionResult FrontPageList()
{
//here I get the product from repository and bring only 2 var product = productRepository.Products.Take(2).OrderBy(p => p.productsID).ToList();
return View(new ProdListViewModel(product));
}
}
here is the view I generate by VS
@model IEnumerable<SalesRep.Domain.ViewModels.TuscanyWeb.ProdListViewModel>
@{
ViewBag.Title = "FrontPageList";
}
<h2>FrontPageList</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
</table>
this is the complete error The model item passed into the dictionary is of type 'SalesRep.Domain.ViewModels.TuscanyWeb.ProdListViewModel', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[SalesRep.Domain.ViewModels.TuscanyWeb.ProdListViewModel]'
on the other hand if in the controller I to this
//List<ProdViewModel> basicObjectList =
// product.ConvertAll(x => new ProdViewModel
// {
// pname = x.pname,
// productsID = x.productsID
// });
and pass basicObjectList to the view i works fine.
Upvotes: 1
Views: 4526
Reputation: 4324
You don't need @model IEnumerable<SalesRep.Domain.ViewModels.TuscanyWeb.ProdListViewModel>
, just @model SalesRep.Domain.ViewModels.TuscanyWeb.ProdListViewModel
. Then, in your for loop just do it like this:
@foreach (var item in Model.ProductsList ) {
Upvotes: 1