Localized ModelMetadata and Caching

359 Views Asked by At

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?

1

There are 1 best solutions below

0
On

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