ComponentModel通过反射显示资源
本文关键字:显示 资源 反射 ComponentModel | 更新日期: 2023-09-27 18:01:33
我正在本地化我的asp.net Mvc应用程序。字符串放在资源文件中。我正在用System.ComponentModel.DataAnnotations.DisplayAttribute属性装饰我的模型,例如:
public class User
{
public virtual Guid Id { get; set; }
[Display(ResourceType = typeof(ModelRes.User), Name = "LogonName")]
public virtual string LogonName { get; set; }
[Display(ResourceType = typeof(ModelRes.User), Name = "Password")]
public virtual string Password { get; set; }
}
每个模型(类)和用户都有一个资源文件。Resx看起来像这样:
LogonName | "Logon name"
Password | "Password"
现在想象一下,对于很多属性,你都明白了。我想做的是:
[CustomDisplay(typeof(ModelRes.User))]
public class User
{
public virtual Guid Id { get; set; }
public virtual string LogonName { get; set; }
public virtual string Password { get; set; }
}
并且仍然可以在我的(razor)视图中使用它:
@Html.LabelFor(m => m.LogonName)
有实现这样的东西的经验吗?
您必须编写一个自定义的ModelMetadataProvider。
然后,您必须使用自定义属性和属性名称设置ModelMetadata
变量的DisplayName
属性。
这里有一些例子/教程
ASP。. NET MVC 3服务位置,第7部分:模型元数据
定制ASP。. NET MVC 2元数据和验证