【发布时间】:2023-03-13 12:05:02
【问题描述】:
我什至不确定 MVC Razor 是否可行,但我想将包含另一个字典的字典传递到我的视图并显示子字典键和值。
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]]}
My Child Dictionary 的值如下:
[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
感谢任何建议。
【问题讨论】:
-
你有 Razor 模板的完整示例,包括模型类型定义吗?
-
如果您创建一个包含 Month、MonthlyAmount 和 TotalYearAmount 成员的类,而不是使用匿名类型,@item.Value.Month 将起作用。有没有理由不用类来代替匿名类型?
-
@Jerry Federspiel 将其添加为答案:D
标签: c# asp.net-mvc razor dictionary