我是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 => 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.generic.eneric.ienumoserth的模型项目。prodListViewModel]'
另一方面,如果在控制器i到此
中//List<ProdViewModel> basicObjectList =
// product.ConvertAll(x => new ProdViewModel
// {
// pname = x.pname,
// productsID = x.productsID
// });
并将BasicObjectList传递给我的视图。
您不需要@model IEnumerable<SalesRep.Domain.ViewModels.TuscanyWeb.ProdListViewModel>
,而只需要@model SalesRep.Domain.ViewModels.TuscanyWeb.ProdListViewModel
。然后,在您的循环中只需这样做:
@foreach (var item in Model.ProductsList ) {