首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >向ViewBag传递列表的ASP.NET MVC

向ViewBag传递列表的ASP.NET MVC
EN

Stack Overflow用户
提问于 2017-01-22 03:13:37
回答 1查看 3.5K关注 0票数 0

我有一个定义为:

代码语言:javascript
复制
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属性对所有技能进行分组

代码语言:javascript
复制
        public async Task<ActionResult> Index()
    {


        var groupedSkills = (from s in db.Skills
                             group s by s.SkillGroup).ToList();
        ViewBag.GroupedSkills = groupedSkills;                   
        return View();
    }

现在,当我在视图中尝试处理以下内容时,此部分可以完美地工作:

代码语言:javascript
复制
@foreach (var skillGroup in ViewBag.GroupedSkills)
{
    <h1>@skillGroup.Key</h1>
    foreach (var item in skillGroup)
    {
        <h2>@item.Name - @item.SkillLevel </h2>
    }

}

我收到一个错误,说:

代码语言:javascript
复制
'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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-01-22 03:35:26

您可以通过以下方式来解决此问题。

group by LINQ查询的结果将是动态的,当在视图中访问时,它的每个项都被视为一个对象。这就是为什么你会看到这个错误。这个问题的解决方案是将group by LINQ查询的结果转换为字典,如下所示。

代码语言:javascript
复制
var groupedSkills = (from s in db.Skills group s by s.SkillGroup).ToDictionary(x => x.Key, x => x.ToList());
ViewBag.GroupedSkills = groupedSkills;

字典现在是KeyValuePair对象的集合,其中SkillGroup是关键字,值是技能列表。您可以将其值呈现为如下所示。

代码语言:javascript
复制
@foreach (var skillGroup in ViewBag.GroupedSkills)
{
    <h1>@skillGroup.Key</h1>
    foreach (var item in skillGroup.Value)
    {
        <h2>@item.Name - @item.SkillLevel </h2>
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41783389

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档