[英]MVC 3 - display value from dictionary in view
I suspect this is simple and I'm just missing it. 我怀疑这很简单,我只是想念它。
I have a view model that has a dictionary as one of its properties. 我有一个视图模型,它有一个字典作为其属性之一。 This dictionary is for populating an HTML select with the Category when I'm editing a record. 这个词典用于在我编辑记录时用类别填充HTML选择。 There is also a property to indicate the selected CategoryID. 还有一个属性指示所选的CategoryID。 However, when I'm just displaying the record I want to display the value of the key/value pair that corresponds with the CategoryID. 但是,当我只显示记录时,我想显示与CategoryID对应的键/值对的值。
My view model: 我的观点模型:
public class ItemEditVM
{
public int ItemID { get; set; }
public int? CategoryID { get; set; }
public string ItemDesc { get; set; }
public Dictionary<int, string> CategorySelect { get; set; }
}
I've tried something like this but I've got the function parameters wrong: 我尝试过类似的东西,但我的函数参数错误了:
@Html.DisplayFor(model => model.CategorySelect.TryGetValue(model.CategoryID, out val))
I've also tried this which fails with no specific error message: 我也试过这个失败,没有特定的错误信息:
@Html.DisplayFor(model => model.CategorySelect.SingleOrDefault(c=> int.Parse(c.Value) == model.CategoryID).Value)
How can I do this? 我怎样才能做到这一点?
Many thanks 非常感谢
THE CORRECT ANSWER (Thanks to Mystere Man) 正确的答案(感谢Mystere Man)
@Html.DisplayFor(model=>model.CategorySelect[Model.CategoryID.Value])
Have you tried: 你有没有尝试过:
@Model.CategorySelect[Model.CategoryID.Value]
Since as you say, CategoryID won't be null, then this should not be a problem.. unless it could be null, in which case you need to do some validation. 正如你所说,CategoryID不会为null,那么这应该不是问题..除非它可以为null,在这种情况下你需要做一些验证。
@foreach(var keyValue in Model.CategorySelect.keys)
{
foreach(var cat in @Model.CategorySelect[keyValue]
{
<p>@cat</p> <!--whatever html you fancy-->
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.