试图创建一个自定义viewmodel类,该类需要2个模型列表或可枚举的模型。当我尝试在视图类中显示它时,出现以下错误。
传递到字典中的模型项的类型为““ Prototype01.ViewModels.StockViewModel”,但此字典需要模型项的类型为'System.Collections.Generic.IList`1 [Prototype01.ViewModels.StockViewModel]“”
我尝试制作单独的视图,并使用简单的模型在视图中进行投影。它工作正常,但是当我尝试获取viewmodel时,效果却不如我预期。
public class StockController : Controller
{
private ApplicationDbContext _context;
public StockController()
{
_context = new ApplicationDbContext();
}
protected override void Dispose(bool disposing)
{
_context.Dispose();
}
// GET: Stock
public ActionResult StockIndex()
{
var batteries = _context.Batteries.ToList();
var rims = _context.Rims.ToList();
var viewmodel = new StockViewModel
{
Batteries = batteries,
Rims = rims
};
return View(viewmodel);
}
}
public class StockViewModel
{
public IEnumerable<Battery> Batteries { get; set; }
public IEnumerable<Rim> Rims { get; set; }
}
@model IEnumerable<Prototype01.ViewModels.StockViewModel>
@{
ViewBag.Title = "StockIndex";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Stock Management</h2>
@if (!Model.Any())
{
<p>We don't have any Batteries yet.</p>
<label class="btn-group">@Html.ActionLink("Add New", "New", "Battery")
</label>
}
else
{
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>battery ID</th>
<th>battery Name</th>
</tr>
</thead>
<tbody>
@foreach (var bt in Model)
{
<tr>
<td> tying to show batteries here</td>
</tr>
}
</tbody>
</table>
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>Rim ID</th>
<th>Rim Name</th>
</tr>
</thead>
<tbody>
@foreach (var rm in Model)
{
<tr>
<td> tying to show Rims here</td>
</tr>
}
</tbody>
</table>
}
我试图将数据存储在控制器方法中,并发送viewmodel以仅显示2个表,其中ID和名称来自数据库表Batteries和Rims
另一方面,我遇到了一个例外 传递到字典中的模型项的类型为'Prototype01.ViewModels.StockViewModel',但是此字典需要模型类型为'System.Collections.Generic.IEnumerable`1 [Prototype01.ViewModels.StockViewModel]”的模型项。答案 0 :(得分:0)
您正在遍历Model,而不是遍历单个枚举数; ViewModel中的电池和轮辋。
因此更改行:
@foreach (var bt in Model)
收件人:
@foreach (var bt in Model.Batteries)
轮辋也一样:
@foreach (var rm in Model)
收件人:
@foreach (var rm in Model.Rims)
也要更改:
@model IEnumerable<Prototype01.ViewModels.StockViewModel>
收件人:
@model Prototype01.ViewModels.StockViewModel