在ASP.NET MVC中从Razor检查字典键

时间:2014-12-23 15:12:22

标签: asp.net-mvc dictionary

我正在开发一个我继承的ASP.NET MVC应用程序。该应用使用Dictionary<string, string> TranslationsDictionary存储在Application对象上。目前,我有以下内容:

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

除非在key中找不到Translations,否则此方法有效。如何从Razor代码中优雅地确保密钥存在于Translations字典中?我似乎无法确定一个好方法。

感谢您的帮助和节日快乐。

2 个答案:

答案 0 :(得分:1)

您只需检查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);
}

我在视图中进行任何计算都不是很有趣,但这应该有效。如果密钥不存在,将返回空字符串。

答案 1 :(得分:1)

您可以使用Dictionary的{​​{3}}方法返回bool,表示Dictionary<TKey, TValue>中是否存在密钥:

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

有几种方法可以迭代Dictionary,这里有一个遍历每个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
}