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

880 views asp.net
3

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

answered question

1 Answer

10

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

posted this

Have an answer?

JD

Please login first before posting an answer.