簡體   English   中英

ASP.NET MVC將列表列表傳遞給ViewBag

[英]ASP.NET MVC Passing a List of Lists to the ViewBag

我有一個實體,其定義為:

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列表上清楚地看到屬性Key,我是否需要以某種方式進行轉換? 我是否需要使skillGroup為非匿名類型? 手表的屏幕截圖

您可以通過以下方式解決此問題。

LINQ分組查詢的結果將是動態的,並且在視圖中訪問它的每個項目都將被視為一個對象。 這就是為什么您看到該錯誤。 解決方案是將LINQ查詢的分組結果轉換為Dictionary,如下所示。

var groupedSkills = (from s in db.Skills group s by s.SkillGroup).ToDictionary(x => x.Key, x => x.ToList());
ViewBag.GroupedSkills = groupedSkills;

詞典現在是KeyValuePair對象的集合,其中Key是SkillGroup,Value是Skills列表。 您可以按如下所示呈現此值。

@foreach (var skillGroup in ViewBag.GroupedSkills)
{
    <h1>@skillGroup.Key</h1>
    foreach (var item in skillGroup.Value)
    {
        <h2>@item.Name - @item.SkillLevel </h2>
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM