【发布时间】:2017-03-01 20:13:40
【问题描述】:
我是 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.IEnumerable`1[SalesRep.Domain.ViewModels.TuscanyWeb. ProdListViewModel]'
另一方面,如果在控制器中我要这样做
//List<ProdViewModel> basicObjectList =
// product.ConvertAll(x => new ProdViewModel
// {
// pname = x.pname,
// productsID = x.productsID
// });
并将 basicObjectList 传递给我工作正常的视图。
【问题讨论】:
-
能否请您也发布您的
FrontPageList.cshtml模板? -
我用视图编辑问题
标签: c# asp.net-mvc