我有一个定义为:
public class Skill
{
public enum Level { Begginer, Intermediate, Advanced }
public int Id { get; set; }
[Display(Name ="Skill Group")]
public string SkillGroup { get; set; }
[Display(Name ="Skill Name")]
public string Name { get; set; }
[Display(Name ="Level")]
public Level SkillLevel { get; set; }
public virtual ICollection<Certificate> Certificates { get; set; }
}在我的控制器中,我尝试根据类的SkillGroup属性对所有技能进行分组
public async Task<ActionResult> Index()
{
var groupedSkills = (from s in db.Skills
group s by s.SkillGroup).ToList();
ViewBag.GroupedSkills = groupedSkills;
return View();
}现在,当我在视图中尝试处理以下内容时,此部分可以完美地工作:
@foreach (var skillGroup in ViewBag.GroupedSkills)
{
<h1>@skillGroup.Key</h1>
foreach (var item in skillGroup)
{
<h2>@item.Name - @item.SkillLevel </h2>
}
}我收到一个错误,说:
'object' does not contain a definition for 'Key'
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'object' does not contain a definition for 'Key'
Source Error:
Line 46: @foreach (var skillGroup in ViewBag.GroupedSkills)
Line 47: {
Line 48: <h1>@skillGroup.Key</h1>
Line 49: foreach (var item in skillGroup)
Line 50: {但是当我调试时,我可以清楚地看到skillGroup列表上的属性键,我需要以某种方式转换它吗?是否需要将skillGroup设置为非无名类型?ScreenShot of the watch for the Variable
发布于 2017-01-22 03:35:26
您可以通过以下方式来解决此问题。
group by LINQ查询的结果将是动态的,当在视图中访问时,它的每个项都被视为一个对象。这就是为什么你会看到这个错误。这个问题的解决方案是将group by LINQ查询的结果转换为字典,如下所示。
var groupedSkills = (from s in db.Skills group s by s.SkillGroup).ToDictionary(x => x.Key, x => x.ToList());
ViewBag.GroupedSkills = groupedSkills;字典现在是KeyValuePair对象的集合,其中SkillGroup是关键字,值是技能列表。您可以将其值呈现为如下所示。
@foreach (var skillGroup in ViewBag.GroupedSkills)
{
<h1>@skillGroup.Key</h1>
foreach (var item in skillGroup.Value)
{
<h2>@item.Name - @item.SkillLevel </h2>
}
}https://stackoverflow.com/questions/41783389
复制相似问题