我有以下模型类
require_once('lib/Twig/Autoloader.php');
Twig_Autoloader::register();
$loader = new Twig_Loader_Filesystem('views');
$twig = new Twig_Environment($loader, array(
//'cache' => 'cache',
'auto_reload' => true
));
然后我对List和Create
都有以下视图public class ProductViewModel
{
public Product Products { get; set; }
public IEnumerable<Product> LProducts { get; set; }
}
public partial class Product
{
public string id { get; set; }
public string detail { get; set; }
}
这是列表的控制器方法
@model albaraka.Models.ProductViewModel
<table class="table">
<tr>
<th>
ID
</th>
<th>
Detail
</th>
</tr>
@foreach (var obj in Model.LProducts)
{
<tr>
<td>
@Html.DisplayFor(modelItem => obj.id)
</td>
<td>
@Html.DisplayFor(modelItem => obj.detail)
</td>
</tr>
}
</table>
<div>
@using ())
{
<div>
<fieldset>
<legend>Account Information</legend>
<div class="editor-label">
@Html.LabelFor(m => m.id)
</div>
<div class="editor-field">
@Html.TextBoxFor(m => m.Products.id)
@Html.ValidationMessageFor(m => m.Products.id)
</div>
<div class="editor-label">
@Html.LabelFor(m => m.Products.detail)
</div>
<div class="editor-field">
@Html.TextBoxFor(m => m.Products.detail)
@Html.ValidationMessageFor(m => m.Products.detail)
</div>
<p>
<input type="submit" value="Submit" />
</p>
</fieldset>
</div>
}
</div>
@section Scripts
{}
但在这里我得到了以下错误
传递到字典中的模型项是类型的 'System.Collections.Generic.List`1 [projectname.Models.Product]',但是 这本词典需要一个类型的模型项 'projectname.Models.ProductViewModel'。
答案 0 :(得分:3)
错误不言自明,您的观点接受@model albaraka.Models.ProductViewModel
而非@model IList<albaraka.Models.ProductViewModel>
。在您的视图中,您使用的是@model albaraka.Models.ProductViewModel
,表示视图所需的模型属于ProductViewModel
类型:
[HttpGet]
public ViewResult Product_List()
{
ProductViewModel viewModelList = new ProductViewModel();
viewModelList.LProducts = (from products in db.AB_Product
where products.details == "Pending"
select products).ToList();
return View(viewModelList);
}
答案 1 :(得分:1)
错误告诉您究竟是什么问题。您正在向视图提供Product对象列表,而不是它期望的ProductModelView。将您的控制器代码更改为:
[HttpGet]
public ViewResult Product_List()
{
ProductViewModel viewModelList = new ProductViewModel();
viewModelList.LProducts = (from products in db.Product
where products.details == "Pending"
select products).ToList();
return View(viewModelList);
}
答案 2 :(得分:1)
嗯,异常文本是不言自明的 - 您将错误的类型传递给视图。
应该是
public ViewResult Product_List()
{
ProductViewModel viewModelList = new ProductViewModel();
viewModelList.LProducts = (from products in db.Product
where products.details == "Pending"
select products).ToList();
return View(viewModelList);
}
答案 3 :(得分:0)
错误的直接原因是您传递的参数(List)和视图(ProductViewModel
类的实例)所期望的类型不匹配。
在您的控制器中,而不是行:
return View(viewModelList.LProducts.ToList());
尝试以下方法:
return View(
new ProductViewModel {LProducts = viewModelList.LProducts.ToList()}
);