简体   繁体   中英

Localized ModelMetadata and Caching

I'm having problems with my localized Model attributes as we decided to not use the build-in localization functionallity.

 public class LocalizedRequiredAttribute : RequiredAttribute
{
    public LocalizedRequiredAttribute(string displayName)
    {
        DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(LocalizedRequiredAttribute), typeof(RequiredAttributeAdapter));

        ErrorMessage = ResourceProvider.Get(string.Format("resValidation{0}Missing", displayName));
    }
}

The problem is that the global culture can be changed by the user but ErrorMessage, DisplayName and stuff is kind of cached by the framework. Any suggestions how to fix this and bind the attributes on runtime?

I finally found a solution for this. You just have to override the FormatErrorMessage Method:

 public class LocalizedRequiredAttribute : RequiredAttribute
{
    private readonly string _displayName;

    public LocalizedRequiredAttribute(string displayName)
    {
        DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(LocalizedRequiredAttribute), typeof(RequiredAttributeAdapter));
        _displayName = displayName;
    }

    public override string FormatErrorMessage(string name)
    {
        return Resource.Get(string.Format("resValidation{0}Missing", _displayName));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM