如何使用DataAnnotations ErrorMessageResourceName自定义资源解决方案

问题描述:

我建设用C#中的MVC Web应用程序。由于该网站将是多语言的,我实现了我自己的ResourceManager。该类负责获取来自取决于电流线程的区域性数据库/缓存所需的资源字符串和正常工作为止。

I'm building a MVC web application with C#. Since the site will be multilingual, I've implemented my own ResourceManager. This class is responsible for fetching the required resource strings from a database/cache depending on the currents thread culture and works fine so far.

我的问题是,我想,当例如使用的必需的一个属性属性使用我的自定义的ResourceManager的解决方案来获取验证错误消息。可以这样做?

My problem is, I'd like to use the my custom ResourceManager solution to fetch validation error messages when for example using the Required Attribute on a property. Can this be done?

的RequiredAttribute允许使用一custom资源管理器:

[Required(
    ErrorMessageResourceType = typeof(CustomResourceManager), 
    ErrorMessageResourceName = "ResourceKey")]
public string Username { get; set; }


更新:

另一种可能性是写你的自定义属性:

Another possibility is to write your custom attribute:

public class CustomRequiredAttribute : RequiredAttribute
{
    public override string FormatErrorMessage(string name)
    {
        return YourCustomResourceManager.GetResource(name);
    }
}