gpt4 book ai didi

c# - 通过 Entity Framework Core 将列表传递给 View

转载 作者:行者123 更新时间:2023-11-30 21:30:33 27 4
gpt4 key购买 nike

我想将产品列表传递给我的 View 。但我不知道我在这里错过了什么。当我运行它时,我遇到了这个异常

InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'System.Runtime.CompilerServices.AsyncTaskMethodBuilder1+AsyncStateMachineBox1[System.Collections.Generic.IList1[DataLayers.Models.mymodel],DataLayers.Services.Repository+d__2]', but this ViewDataDictionary instance requires a model item of type 'System.Collections.Generic.IEnumerable`1[DataLayers.Models.mymodel]'.

这是我的IRepository

Task<IList<mymodel>> GetAllProductsAsync();

这是我的Repository(为简单起见省略了上下文注入(inject))

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>

最佳答案

考虑改变:

public IActionResult Products()
{
return View(_IRepository.GetAllProductsAsync());
}

收件人:

public async Task<IActionResult> Products()
{
return View(await _IRepository.GetAllProductsAsync());
}

关于c# - 通过 Entity Framework Core 将列表传递给 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54190218/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com