asp.net-mvc – 使用DisplayAttribute和自定义资源提供程序的ASP.NET MVC 3本地化

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 使用DisplayAttribute和自定义资源提供程序的ASP.NET MVC 3本地化前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用自定义资源提供程序从数据库获取资源字符串.这可以在ASP.NET中正常工作,我可以将资源类型定义为字符串. MVC 3中的模型属性的元数据属性(如[范围],[显示],[必需])要求将资源作为参数的类型,其中ResourceType是.resx文件生成代码隐藏类的类型.
[Display(Name = "Phone",ResourceType = typeof(MyResources))]
    public string Phone { get; set; }

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

我想要这样的东西:

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

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

解决方法

您可以扩展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);
                }
            }
        }
    }
}

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

public string GetLocalLocalizedString(string key){
    return _resourceSet.GetString(key);
}

显然,您将需要添加错误处理并设置resourceReader.更多信息here

这样,然后用新的属性来装饰你的模型,传递你要获取值的资源的关键字,像这样

[LocalizedDisplayName("Title")]

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

原文链接:https://www.f2er.com/aspnet/250179.html

猜你在找的asp.Net相关文章