我是Ninjet和Mvc的新手。我知道这个错误意味着我将错误的类型传递给视图。但我无法弄清楚错误在哪里。这是我的课程
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;
}
}
这是我的控制。如你所见,我正在使用ninjet。我检查我正在返回产品列表中的2个产品。但是
public class ProductController : ControllerBase
{
internal readonly IProductRepository productRepository;
public ProductController(IProductRepository productRepository)
{
this.productRepository = productRepository;
}
// GET: Product
public ActionResult FrontPageList()
{
//这里我从存储库中获取产品,只带2个 var product = productRepository.Products.Take(2).OrderBy(p =&gt; p.productsID).ToList();
return View(new ProdListViewModel(product));
}
}
这是我由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>
这是完整的错误 传递到字典中的模型项的类型为“SalesRep.Domain.ViewModels.TuscanyWeb.ProdListViewModel”,但此字典需要类型为“System.Collections.Generic.IEnumerable”1 [SalesRep.Domain.ViewModels.TuscanyWeb]的模型项。 ProdListViewModel]'
另一方面,如果在控制器I中,
//List<ProdViewModel> basicObjectList =
// product.ConvertAll(x => new ProdViewModel
// {
// pname = x.pname,
// productsID = x.productsID
// });
并将basicObjectList传递给视图我工作正常。
答案 0 :(得分:0)
您不需要@model IEnumerable<SalesRep.Domain.ViewModels.TuscanyWeb.ProdListViewModel>
,只需@model SalesRep.Domain.ViewModels.TuscanyWeb.ProdListViewModel
。然后,在你的for循环中,就这样做:
@foreach (var item in Model.ProductsList ) {