本地化的ModelMetadata和缓存

时间:2014-08-13 08:37:47

标签: asp.net-mvc asp.net-mvc-4 attributes modelmetadata

由于我们决定不使用内置本地化功能,因此我的本地化模型属性出现问题。

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

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

问题在于用户可以更改全局文化,但是ErrorMessage,DisplayName和stuff是由框架缓存的。任何建议如何解决这个问题并绑定运行时的属性?

1 个答案:

答案 0 :(得分:2)

我终于找到了解决方案。您只需要覆盖FormatErrorMessage方法:

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