我想将产品列表传递给我的视图。但我不知道我在这里想念的是什么。当我运行它时,我会遇到这种异常情况
InvalidOperationException:传递给ViewDataDictionary的模型项的类型为'System.Runtime.CompilerServices.AsyncTaskMethodBuilder1 + AsyncStateMachineBox1 [System.Collections.Generic.IList1 [DataLayers.Models.mymodel],DataLayers.Services.Repository + d__2]' ,但此ViewDataDictionary实例需要一个类型为'System.Collections.Generic.IEnumerable`1 [DataLayers.Models.mymodel]'的模型项。
这是我的 IRepository
Task<IList<mymodel>> GetAllProductsAsync();
这是我的 存储库 (为简单起见,省略了上下文注入)
public async Task<IList<mymodel>> GetAllProductsAsync()
{
return await _context.mymodel.ToListAsync();
}
这是 MyController
private readonly IRepository _IRepository;
public MyController(IRepository ThisController)
{
_IRepository = ThisController;
}
public IActionResult Products()
{
return View(_IRepository.GetAllProductsAsync());
}
最后是 myView
@model IEnumerable<DataLayers.Models.mymodel>
<table>
@foreach (var item in Model)
{
<tr class="table-row">
<td>
<img src="@Html.DisplayFor(m => item.DishImg)">
</td>
<td>
<p>@Html.DisplayFor(m => item.Productname)</p>
</td>
<td>
<p>@Html.DisplayFor(m => item.ProductInfo)</p>
</td>
<td>
<p>@Html.DisplayFor(m => item.ProductPrice)</p>
</td>
</tr>
}
</table>
答案 0 :(得分:3)
考虑更改以下内容:
public IActionResult Products()
{
return View(_IRepository.GetAllProductsAsync());
}
收件人:
public async Task<IActionResult> Products()
{
return View(await _IRepository.GetAllProductsAsync());
}