我是Ninjet和Mvc的新手。我知道這個錯誤意味着我將錯誤的類型傳遞給視圖。但我無法弄清楚錯誤在哪裏。這裏是我的課MVC 5錯誤,但這本字典需要一個'System.Collections.Generic.IEnumerable'類型的模型項目
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 變種產品= productRepository.Products.Take(2).OrderBy(P => 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]'
的模型項目,另一方面如果在c ontroller我對此
//List<ProdViewModel> basicObjectList =
// product.ConvertAll(x => new ProdViewModel
// {
// pname = x.pname,
// productsID = x.productsID
// });
並將basicObjectList傳遞給視圖我工作正常。
你能否也請張貼您的'FrontPageList.cshtml'模板? – eminlala
我用視圖編輯問題 – user6272884