使用DisplayAttribute和自定义资源提供程序进行ASP.NET MVC 3本地化

slf*_*fan 14 asp.net-mvc localization internationalization displayattribute asp.net-mvc-3

我使用自定义资源提供程序从数据库中获取资源字符串.这适用于ASP.NET,我可以将资源类型定义为字符串.MVC 3中模型属性的元数据属性(如[Range],[Display],[Required])需要Resource的类型作为参数,其中ResourceType是.resx文件生成的代码隐藏类的类型.

    [Display(Name = "Phone", ResourceType = typeof(MyResources))]
    public string Phone { get; set; }
Run Code Online (Sandbox Code Playgroud)

因为我没有.resx文件,所以这样的类不存在.如何将模型属性与自定义资源提供程序一起使用?

我想要这样的东西:

    [Display(Name = "Telefon", ResourceTypeName = "MyResources")]
    public string Phone { get; set; }
Run Code Online (Sandbox Code Playgroud)

System.ComponentModel中的DisplayNameAttribute为此目的具有可覆盖的DisplayName属性,但DisplayAttribute类是密封的.对于验证属性,不存在相应的类.

Mar*_*cki 7

我提出的最干净的方法就是覆盖DataAnnotationsModelMetadataProvider.这是一篇关于如何做到这一点的非常简洁的文章.

http://buildstarted.com/2010/09/14/creating-your-own-modelmetadataprovider-to-handle-custom-attributes/


pol*_*ata 4

您可以扩展 DisplayNameAttribute 并覆盖 DisplayName 字符串属性。我有这样的东西

    public class LocalizedDisplayName : DisplayNameAttribute
    {
        private string DisplayNameKey { get; set; }   
        private string ResourceSetName { get; set; }   

        public LocalizedDisplayName(string displayNameKey)
            : base(displayNameKey)
        {
            this.DisplayNameKey = displayNameKey;
        }


        public LocalizedDisplayName(string displayNameKey, string resourceSetName)
            : base(displayNameKey)
        {
            this.DisplayNameKey = displayNameKey;
            this.ResourceSetName = resourceSetName;
        }

        public override string DisplayName
        {
            get
            {
                if (string.IsNullOrEmpty(this.GlobalResourceSetName))
                {
                    return MyHelper.GetLocalLocalizedString(this.DisplayNameKey);
                }
                else
                {
                    return MyHelper.GetGlobalLocalizedString(this.DisplayNameKey, this.ResourceSetName);
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

对于MyHelper,方法可以是这样的:

public string GetLocalLocalizedString(string key){
    return _resourceSet.GetString(key);
}
Run Code Online (Sandbox Code Playgroud)

显然,您需要添加错误处理并进行resourceReader设置。更多信息请点击此处

这样,您就可以用新属性装饰您的模型,传递您想要从中获取值的资源的键,如下所示

[LocalizedDisplayName("Title")]
Run Code Online (Sandbox Code Playgroud)

然后Html.LabelFor将自动显示本地化的文本。