在MVC Razor视图中显示字典中的字典值

时间:2015-07-08 21:35:22

标签: c# asp.net-mvc razor dictionary

我甚至不确定MVC Razor是否可行,但我想将包含另一个Dictionary的词典传递给我的视图并显示子词典键和值。

public Dictionary<int, dynamic> Getdata(DateInfo dataInfo)
{

//Create a parent dictionary
Dictionary<int, dynamic> parentDict = new Dictionary<int, dynamic>();

//Load the child dictionary
for (int i = 0; i < list.Count; i++)
{
     //Create a child dictionary to store all values
     Dictionary<int, dynamic> dict = new Dictionary<int, dynamic>();

     parentDict[i] = dict;
     parentDict[i].Clear();
    if (beginningYear < DateTime.Now.Year)
    {
         //...code left out for brevity

        if (NumberOfYears > 1)
        {
            for(int j = 1; j < NumberOfYears; j++)
            {
               beginningYear = beginningYear + 1;

               //...code left out for brevity

               dict.Add(beginningYear, new { Month = 12, MonthlyAmount = nextYearAmount.premium, TotalYearAmount = TotalYearAmount });
            }
        }
     else
     {
         //...code left out for brevity
     }
}
return parentDict;

我的父词典值如下所示:

[0] = {[0, System.Collections.Generic.Dictionary`2[System.Int32,System.Object]]}

[1] = {[1, System.Collections.Generic.Dictionary`2[System.Int32,System.Object]]}

我的孩子词典的价值如下:

[0] { Month = 5, MonthlyAmount = 99.90, TotalYearAmount = 499.50 }

[1] { Month = 12, MonthlyAmount = 399.90, TotalYearAmount = 1499.50 }

[2] { Month = 12, MonthlyAmount = 499.90, TotalYearAmount = 1794.50 }
[0] { Month = 9, MonthlyAmount = 999.90, TotalYearAmount = 6499.50 }

[1] { Month = 12, MonthlyAmount = 3.90, TotalYearAmount = 39.50 }

在视图中:

 @foreach (var item in Model.MyDictionary[0])
 { 
     @item.Value
 }

该代码将显示子值,即:

 { Month = 5, MonthlyAmount = 99.90, TotalYearAmount = 499.50 }

是否可以引用Month,MonthlyAmount,TotalYearAmount?

     @item.Value.Month 

不起作用。 'object'不包含'Month'的定义

我想通过父词典引用孩子。如果我使用:

 @foreach (var item in Model.MyDictionary[1])
 { 
     @item.Value
 }

将显示

 { Month = 9, MonthlyAmount = 999.90, TotalYearAmount = 6499.50 }

此代码无法使用,但我希望获得以下值:

 @foreach (var item in Model.MyDictionary[0][1])
 { 
     @item.Value.TotalYearAmount 
 }

,显示值:1499.50

感谢任何建议。

2 个答案:

答案 0 :(得分:1)

更改行

dict.Add(beginningYear, new { Month = 12, MonthlyAmount = nextYearAmount.premium, TotalYearAmount = TotalYearAmount });

使用ExpandoObject

dynamic expandoObject = new ExpandoObject();
expandoObject.Month = 12;
expandoObject.MonthlyAmount = nextYearAmount.premium;
expandoObject.TotalYearAmount = TotalYearAmount;
dict.Add(beginningYear, expandoObject);

如果您的词典较长,可以使用以下链接将其转换为方法:http://theburningmonk.com/2011/05/idictionarystring-object-to-expandoobject-extension-method/

答案 1 :(得分:0)

您可以使用dynamic代替var,如下所示:

 @foreach (dynamic item in Model.MyDictionary[0][1])
 { 
     @item.Value.TotalYearAmount 
 }