简体   繁体   中英

How to display Dictionary values inside a Razor View (MVC)

Sorry I am new to Dictionaries and passing them down to the view

I have all the data needed to be sent down to View.

Inside the ViewModel, this is the Dictionary setup

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

Within the view, I am looking to see if the certain key,value pair exists.

@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>
}

I do not want to do within a for loop to display each 'ImageDetail'. This works fine if an index of 0 is there, otherwise I receive an error that 'The given key was not present in the dictionary.'

If the key does not exist, should it not go through to the else?

Thanks

The reason is Dictionary needs an implementation of Object.GetHashCode() . As your key is nullable and null doesnot have any implementation so no HashCode.

There are different ways of safe iterating a dictionary. I am also not a big fan of any calculations in View, but here it goes:

@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;
    }
}

Useful reading on the error here:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM