xam developer
xam developer

Reputation: 1983

Checking for Dictionary key from Razor in ASP.NET MVC

I am working on an ASP.NET MVC app that I've inherited. The app uses a Dictionary<string, string> for Translations. That Dictionary is stored on the Application object. Currently, I have the following:

@foreach (var key in Model.MyDictionary.Keys)
{
  var definition = Model.MyDictionary[key];
  ViewDataDictionary viewData = new ViewDataDictionary();
  viewData["key"] = key;
  viewData["value"] = ((Dictionary<string, string>)(HttpContext.Current.Application["Translations"]))[key];
  Html.RenderPartial("~/Views/Shared/_Definition.cshtml", definition, viewData);
}

This approach works except if the key is not found in Translations. How can I elegantly ensure that the key exists in the Translations dictionary from my Razor code? I can't seem to identify a good way to do this.

Thank you for your help and happy holidays.

Upvotes: 2

Views: 6399

Answers (2)

trashr0x
trashr0x

Reputation: 6565

You can use the ContainsKey method of Dictionary which returns a bool indicating whether a key exists in a Dictionary<TKey, TValue>:

@if (Dictionary.ContainsKey("SomeKey") == true)
{
    //"SomeKey" present
}
else
{
    //"SomeKey" not present
}

There are several ways to iterate through a Dictionary, here is one iterating through each KeyValuePair:

@foreach(KeyValuePair<string, string> entry in Model.MyDictionary)
{
    //entry.Key with it's corresponding entry.Value can now be used in your code
    viewData["key"] = entry.Key;
    viewData["value"] = //check if Translations.ContainsKey(entry.Key) here
}

Upvotes: 1

Vsevolod Goloviznin
Vsevolod Goloviznin

Reputation: 12324

You can just check if the key exists in the Dictionary.

@{
   var translations = ((Dictionary<string, string>)(HttpContext.Current.Application["Translations"]));
}
@foreach (var key in Model.MyDictionary.Keys)
{
  var definition = Model.MyDictionary[key];
  ViewDataDictionary viewData = new ViewDataDictionary();
  viewData["key"] = key;
  viewData["value"] = translations.ContainsKey(key) ? translations[key] : string.Empty;
  Html.RenderPartial("~/Views/Shared/_Definition.cshtml", definition, viewData);
}

I'm not a fun of doing any calculations in the view, but this should work. If the key doesn't exist an empty string will be returned.

Upvotes: 1

Related Questions