我有以下模型类
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; }
}
然后我对 List 和 Create 都有以下 View
@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
{}
这是列表的 Controller 方法
[HttpGet]
public ViewResult Product_List()
{
ProductViewModel viewModelList = new ProductViewModel();
viewModelList.LProducts = from products in db.Product
where products.details == "Pending"
select products;
return View(viewModelList.LProducts.ToList());
}
但是这里我遇到了以下错误
The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[projectname.Models.Product]', but this dictionary requires a model item of type 'projectname.Models.ProductViewModel'.
最佳答案
错误不言自明,您的观点接受@model albaraka.Models.ProductViewModel
不是@model IList<albaraka.Models.ProductViewModel>
.在您看来,您正在使用 @model albaraka.Models.ProductViewModel
这表明 View 期望的模型类型为 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);
}
关于c# - 在 asp.net mvc 的同一 View 中列出和创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35059999/