【发布时间】:2015-05-19 12:55:22
【问题描述】:
我通过以下代码在资源的 DisplayFormat 中设置 NullDisplayText
public class LocalizedDisplayFormatAttribute : DisplayFormatAttribute
{
private readonly PropertyInfo _propertyInfo;
public LocalizedDisplayFormatAttribute(string resourceKey, Type resourceType)
: base()
{
this._propertyInfo = resourceType.GetProperty(resourceKey, BindingFlags.Static | BindingFlags.Public);
if (this._propertyInfo == null)
{
return;
}
base.NullDisplayText = (string)this._propertyInfo.GetValue(this._propertyInfo.DeclaringType, null);
}
public new string NullDisplayText
{
get
{
return base.NullDisplayText;
}
set
{
base.NullDisplayText = value;
}
}
}
我使用的默认文化是“en-US”,一旦我将文化更改为 es-AR 并加载页面,它就可以正常工作,但是当我将文化更改回 en-US 时,字段不会被转换回来。
我通过以下方式改变文化
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
try
{
HttpCookie cookie = HttpContext.Current.Request.Cookies.Get("CurrentCulture");
string culutureCode = cookie != null && !string.IsNullOrEmpty(cookie.Value) ? cookie.Value : "en";
CultureInfo ci = new CultureInfo(culutureCode);
System.Threading.Thread.CurrentThread.CurrentUICulture = ci;
System.Threading.Thread.CurrentThread.CurrentCulture =
CultureInfo.CreateSpecificCulture(ci.Name);
}
catch
{
}
}
我在 ViewModel 中使用 DisplayFormat 属性作为
public class AlarmCodeDetailsViewModel
{
/// <summary>
/// Gets or sets the alarm code ID
/// </summary>
public int AlarmCodeID { get; set; }
/// <summary>
/// Gets or sets the alarm code
/// </summary>
[LocalizedDisplayName("Label_AlarmCode")]
[LocalizedDisplayFormatAttribute("Warning_NullDisplayText", typeof(Properties.Resources), HtmlEncode = false)]
public string Code { get; set; }
/// <summary>
/// Gets or sets the Description
/// </summary>
[LocalizedDisplayName("Label_Description")]
[LocalizedDisplayFormatAttribute("Warning_NullDisplayText", typeof(Properties.Resources), HtmlEncode = false)]
public string Description { get; set; }
/// <summary>
/// Gets or sets the Notes
/// </summary>
[LocalizedDisplayName("Label_Notes")]
[LocalizedDisplayFormatAttribute("Warning_NullDisplayText", typeof(Properties.Resources), HtmlEncode = false)]
public string Notes { get; set; }
}
【问题讨论】:
-
你们如何改变文化?请分享您的更改方法/代码。请使用 LocalizedDisplayFormatAttribute 分享您的 View Model 代码声明。
-
@Dave Alperovich:我已经编辑了我的问题
-
请帮帮我。我对问题中的一些措辞感到困惑。你说但是当我改变文化时它不会影响NullDisplayText,它只设置一次我读到这意味着你的应用程序读取文化设置一次并设置
NullDisplayText一次。这可能不是你的意思,因为文化只会设置一次,所以似乎没有问题。 -
我猜你的意思是 NullDisplayText 的设置应该与它不同。如果是这样,请更详细地解释。您获得的文化是什么,NullDisplayText 的预期价值与您获得的价值是什么。
-
@DaveAlperovich:我使用的默认文化是“en-US”,一旦我将文化更改为 es-AR 并加载页面,它的工作正常,但是当我将文化更改回 en-US字段没有被转换回来。
标签: c# asp.net-mvc asp.net-mvc-3 asp.net-mvc-4