我有一些包含国家 ISO 代码的模型。我想用实际的国家名称来显示这些,而不仅仅是 ISO 值。
所以一般来说,我的模型中有键,我在字典中有这些键的定义,我想在 UI 中显示定义。
最近主要在 WPF 中工作,在那里我将创建一个转换器,只要我想转换一个值(甚至是双向的),我就可以在 UI 绑定(bind)中引用它。如果 ASP.MVC 中有一个类似的开箱即用的概念,那将是理想的。
或者,我可以将国家/地区名称作为属性添加到模型中,但这感觉很笨拙。
我当然可以推出自己的自定义转换器解决方案,但更愿意坚持最佳实践,因此非常感谢任何指导。
最佳答案
HtmlHelper 可能是您问题的优雅解决方案。
首先,像这样声明一个 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);
}
}
要在您的 View 中使用这些助手:
@Html.ISOToCountry(Model.ISO) //Print the country
@Html.CountryToISO("England") //Print the ISO
关于c# - ASP.MVC 的显示值转换器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30314737/