【问题标题】:How to display Dictionary values inside a Razor View (MVC)如何在 Razor 视图 (MVC) 中显示字典值
【发布时间】:2018-11-07 01:41:42
【问题描述】:

对不起,我是字典的新手并将它们传递给视图

我有所有需要发送到 View 的数据。

在 ViewModel 内部,这是字典设置

public virtual Dictionary<int?, ImageListItemDto> ImageDictionary { get; set; }

在视图中,我正在查看某个键值对是否存在。

@if (Model != null & Model.ImageDictionary != null && !String.IsNullOrEmpty(Model.ImageDictionary[0].ImageDetail))
{
    <div>@Model.ImageDictionary[0].ImageDetail</div>
}
else
{
    <div>ImageDetails are not there</div>
}

我不想在 for 循环中显示每个“ImageDetail”。如果存在 0 的索引,这可以正常工作,否则我会收到“字典中不存在给定键”的错误。

如果key不存在,不应该通过else吗?

谢谢

【问题讨论】:

    标签: asp.net-mvc dictionary razor


    【解决方案1】:

    原因是 Dictionary 需要实现Object.GetHashCode()。由于您的密钥可以为空,并且 null 没有任何实现,因此没有 HashCode。

    有多种安全迭代字典的方法。我也不喜欢 View 中的任何计算,但这里是这样的:

    @if (Model != null & Model.ImageDictionary != null)
    {
        foreach(KeyValuePair<string, string> dictValue in Model.ImageDictionary)
        {
           viewData["key"] = dictValue.Key;
           viewData["value"] = (Dictionary<int?, ImageListItemDto>)Model.ImageDictionary.ContainsKey(dictValue.Key) ? (Dictionary<int?, ImageListItemDto>)Model.ImageDictionary[dictValue.Key] : string.Empty;
        }
    }
    

    这里的错误有用的阅读:

    C# Dictionary - The given key was not present in the dictionary

    【讨论】:

      猜你喜欢
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 2014-09-20
      • 2014-10-15
      • 1970-01-01
      • 1970-01-01
      • 2013-04-05
      • 2013-06-26
      相关资源
      最近更新 更多