在数据库中使用DisplayName进行MVC4本地化
本文关键字:进行 MVC4 本地化 DisplayName 数据库 | 更新日期: 2023-09-27 18:04:20
我有一个MVC4网站,有不同的资源文件链接到它,本地化工作很好。
但是我想做的是从数据库中获取值,而不是处理resx文件。
我扩展了"DisplayNameAttribute"类,使其接受一个键(整数)和一个CultureInfo对象,并使用它们从数据库中检索值。
我想从CultureInfo的东西是它的字符串表示(例如:"en-US"或"fr-FR")。
我的问题是,我可以将整数传递给扩展类的构造函数,但不能传递CultureInfo。
扩展属性的代码示例:public class LocalizedDisplayNameAttribute : DisplayNameAttribute
{
private int ResourceKey { get; set; }
private CultureInfo Culture { get; set; }
public LocalizedDisplayNameAttribute(int resourceKey, CultureInfo culture)
{
ResourceKey = resourceKey;
Culture = culture;
}
public override string DisplayName
{
get
{
string displayName = "Get from database.. TEST";
return string.IsNullOrEmpty(displayName) ? string.Format("[[{0}]]", ResourceKey) : displayName;
}
}
}
我想做什么:
[LocalizedDisplayName(1, Thread.CurrentThread.CurrentUICulture))]
public string userName { get; set; } //The full name of the user
或者更好:
private CultureInfo culture = Thread.CurrentThread.CurrentUICulture;
[LocalizedDisplayName(1, culture))]
public string userName { get; set; } //The full name of the user
我的问题是,我该怎么做?
这个问题的答案是由Ksven和Tomi Lammi在评论中提供的:
由于Thread.CurrentThread.CurrentUICulture不是编译时值,因此它不能作为LocalizedDisplayName属性的参数提供。因此,解决方案是在attribute方法中使用它,而不是作为参数提供:
public override string DisplayName
{
get
{
var culture = Thread.CurrentThread.CurrentUICulture;
var displayName = db.sp_getValueFromDatabase(id, culture.Name).firstOrDefault();
}
}
因为我不能接受评论作为一个公认的答案,我已经做出了我自己的回答。如果上面的评论者可以把他们的解决方案作为答案,我将把他们的答案作为接受的答案。