ASP.NET MVC 3 localization with DisplayAttribute and custom resource provider

天大地大妈咪最大 提交于 2019-11-28 10:54:06

You can extend the DisplayNameAttribute and override the DisplayName string property. I have something like this

    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);
                }
            }
        }
    }
}

For MyHelper, the methods can be something like this:

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

Obviously you will need to add error handling and have the resourceReader set up. More info here

With this, you then decorate your model with the new attribute, passing the key of the resource you want to get the value from, like this

[LocalizedDisplayName("Title")]

Then the Html.LabelFor will display the localized text automatically.

The most cleanest way I came up with is to override DataAnnotationsModelMetadataProvider. Here's a very neat article on how to do this.

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

I think you would have to override the DataAnnotations properties to localize them with a DB resource provider. You could inherit from the current ones, and then specify further properties such as DB connection string to use when getting the resources from your custom provider.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!