猿问

通过 Entity Framework Core 将列表传递给视图

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


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();

    }

这是我的控制器


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>


慕桂英546537
浏览 123回答 1
1回答

慕桂英4014372

考虑改变:public IActionResult Products(){&nbsp; return View(_IRepository.GetAllProductsAsync());}至:public async Task<IActionResult> Products(){&nbsp; return View(await _IRepository.GetAllProductsAsync());}
随时随地看视频慕课网APP
我要回答