简体   繁体   English

显示值转换器,用于ASP.MVC

[英]Display value converter for ASP.MVC

I have a few models that contain country ISO codes. 我有一些包含国家/地区ISO代码的模型。 I would like to display these with the actual country name instead of just the ISO value. 我想用实际的国家名称显示这些,而不仅仅是ISO值。

So in a generic sense, I have keys in my model, I have the definition of those keys in a dictionary, I would like to display the definition in the UI. 因此,从一般意义上讲,我在模型中有键,在字典中有这些键的定义,我想在UI中显示定义。

Having recently worked mostly in WPF, there I would create a converter which I could just reference in the UI binding whenever I wanted to translate a value (even bidirectional). 在最近主要在WPF中工作之后,我将创建一个转换器,每当我要转换值(甚至双向)时,都可以在UI绑定中引用该转换器。 If there is a similar out-of-the-box concept in ASP.MVC that would be ideal. 如果ASP.MVC中有类似的即用型概念,那将是理想的选择。

Alternatively I could add the country names as attributes to the model, but that feels kludgy. 或者,我可以将国家/地区名称作为属性添加到模型中,但是感觉很笨拙。

I could certainly roll my own custom converter solution, but would prefer to stick to best practices so any guidance is much appreciated. 我当然可以推出自己的自定义转换器解决方案,但是更愿意遵循最佳实践,因此非常感谢任何指导。

A HtmlHelper might be an elegant solution for your problem. HtmlHelper可能是解决您问题的理想解决方案。

First, you declare a HtmlHepler like this: 首先,您需要像这样声明一个HtmlHepler:

public static class CountryHTMLHelpers
 {
      //Initialize your dictionary here
      public static Dictionary<string, string> CountryDictionary;          

      public static IHtmlString ISOToCountry(this HtmlHelper helper, string iso)
      {
          string countryName = CountryDictionary[iso];
          return new HtmlString(countryName);
      }

      public static IHtmlString CountryToISO(this HtmlHelper helper, string country)
      {
          string iso = CountryDictionary.FirstOrDefault(x => x.Value == country).Key;
          return new HtmlString(iso);
      }
}

To use these helpers in your views: 要在您的视图中使用这些助手:

@Html.ISOToCountry(Model.ISO) //Print the country
@Html.CountryToISO("England") //Print the ISO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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