简体   繁体   中英

Passing a list to a view by Entity Framework Core

I want to pass a list of products to my view. but I Don't know what I'm missing here. When I run it i face with this exception

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]'.

This is my IRepository

Task<IList<mymodel>> GetAllProductsAsync();

And here is my Repository (Context injection is omitted for the sake of simplicity )

public async Task<IList<mymodel>> GetAllProductsAsync()
    {
        return await _context.mymodel.ToListAsync();
    }

This is MyController

private readonly IRepository _IRepository;
public MyController(IRepository ThisController)
{
      _IRepository = ThisController;
}


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

And finally Here is 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>

Consider change from:

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

To:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM