0

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

tereško
  • 58,060
  • 25
  • 98
  • 150
drai29
  • 141
  • 1
  • 3
  • 19

1 Answers1

0

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

Gauravsa
  • 6,330
  • 2
  • 21
  • 30