我需要渲染事件(游戏)列表
Grouped by
CreateDate
在控制器中我有
public ActionResult Index()
{
var gs = db.Games.Include(p => p.Activity).GroupBy(e => e.CreateDate);
return View(gs.ToList());
}
在我看来
@model IEnumerable<Game>
<h2>Games List:</h2>
<table>
@foreach (Game e in Model)
{
<thead>
<tr>
<td colspan="2">
<b>@e.CreateDate</b>
</td>
</tr>
</thead>
}
<tr>
<td>
<b>@e.GameStartTime - @e.GameEndTime</b>
</td>
<td>
<b>@e.Activity.ActivityDescription</b>
</td>
</tr>
</table>
但我收到此错误
传入字典的模型项的类型为“System.Collections.Generic.List
2[System.DateTime,MapApp.Models.Event.Event]]”,但该字典需要类型为“System”的模型项.Collections.Generic.IEnumerable`1[MapApp.Models.Event.Event]'.1[System.Linq.IGrouping
我做错了什么?
该视图接受
IEnumerable<Game>
类型的模型,它是游戏的集合,基本上不被任何东西聚集。
您想要传递分组集合,因此正确的类型是
IEnumerable<IGrouping<DateTime, Game>>
:
@model IEnumerable<IGrouping<DateTime, Game>>
迭代此操作将产生每个组,即
IGrouping<DateTime, Game>
实例。您可以通过调用 Key
属性来获取每个组密钥。
迭代
IGrouping<DateTime, Game>
将为您提供该特定组中的所有 Game
实例。
该错误是不言自明的。您当前的代码使用 GroupBy 方法,该表达式的结果将是
IQueryable<IGrouping<DateTime, Game>>
类型,并且您将其传递给视图。但你的观点是强类型的 IEnumerable<Game>
。这就是您收到类型不匹配错误的原因。
您应该为分组数据创建一个视图模型并使用它。
public class GroupedGame
{
public DateTime CreatedDate { set;get;}
public IEnumerable<Game> Games {set;get;}
}
现在在你的行动方法中,
var groupedData = db.Games.Include(p => p.Activity).GroupBy(e => e.CreateDate)
.Select(x=>new GroupedD { CreatedDate = x.Key, Games = x }).ToList();
return View(groupedData);
现在在您的视图中,它被强类型化为我们新视图模型的集合
@model IEnumerable<GroupedGame>
<table>
@foreach(var group in Model)
{
<tr>
<td>@group.CreatedDate.ToString()</td>
<td>
@foreach(var g in group.Games)
{
<p>@g.Name</p>
}
</td>
</tr>
}
</table>