如何在单个视图中使用多个模型 asp.net core 2.2 mvc?

How to use multiple models in single view asp.net core 2.2 mvc?

我试图在 1 个视图中使用两个模型,两个模型 return 不同的数据,第一个包含 winners list,第二个包含 challenges。 我已经创建了自定义视图模型:

  public class CustomViewModel
{
    public IEnumerable<Challenges> challenges { get; set; }
    public IEnumerable<ChallengesWinners> challengeswinners { get; set; }
}

和控制器ChallengesController:

public async Task<IActionResult> Index()

{

 var model = new CustomViewModel
 {
  challenges = _context.Challenges.ToListAsync(),  //showing error here red line conversion error
  challengeswinners = _context.Challenges.ToListAsync()//showing error here red line conversion error
 };

return View("Index", model);
}

并且视图包含:

@model CustomViewModel
@{
ViewData["Title"] = "Index";
Layout = "~/Views/Shared/_LayoutChallenges.cshtml";
 }
<html>
<body>
   @foreach (var item in Model.challenges)
   {
      @Html.DisplayFor(modelItem => item.ChallengeName)
    }
   @foreach (var item in Model.challengeswinners)
   {
     @Html.DisplayFor(modelItem => item.ChallengeName)
    }

试试这个:

 var model = new CustomViewModel
 {
     challenges = await _context.Challenges.ToListAsync(),  
     challengeswinners = await _context.Challenges.ToListAsync()
 };