Luk*_*Led 5 asp.net asp.net-mvc localization data-annotations asp.net-mvc-2
我想在我的ASP.NET MVC应用程序中使用DataAnnotations.我有强类型资源类,并希望在我的视图模型中定义:
[DisplayName(CTRes.UserName)]
string Username;
Run Code Online (Sandbox Code Playgroud)
CTRes是我的资源,自动生成类.不允许以上定义.还有其他解决方案吗?
在.NET 4.0中添加了DisplayAttribute,允许您指定资源字符串:
[Display(Name = "UsernameField")]
string Username;
Run Code Online (Sandbox Code Playgroud)
如果您还不能使用.NET 4.0,那么您可以编写自己的属性:
public class DisplayAttribute : DisplayNameAttribute
{
public DisplayAttribute(Type resourceManagerProvider, string resourceKey)
: base(LookupResource(resourceManagerProvider, resourceKey))
{
}
private static string LookupResource(Type resourceManagerProvider, string resourceKey)
{
var properties = resourceManagerProvider.GetProperties(
BindingFlags.Static | BindingFlags.NonPublic);
foreach (var staticProperty in properties)
{
if (staticProperty.PropertyType == typeof(ResourceManager))
{
var resourceManager = (ResourceManager)staticProperty
.GetValue(null, null);
return resourceManager.GetString(resourceKey);
}
}
return resourceKey;
}
}
Run Code Online (Sandbox Code Playgroud)
您可以这样使用:
[Display(typeof(Resources.Resource), "UsernameField"),
string Username { get; set; }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4425 次 |
| 最近记录: |