C# 如何将 DataAnnotations ErrorMessageResourceName 与自定义资源解决方案一起使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2347650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use DataAnnotations ErrorMessageResourceName with custom Resource Solution
提问by Mats
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.
我正在用 C# 构建一个 MVC Web 应用程序。由于该站点将支持多种语言,因此我实现了自己的 ResourceManager。这个类负责根据当前线程文化从数据库/缓存中获取所需的资源字符串,并且到目前为止工作正常。
My problem is, I'd like to use the my custom ResourceManager solution to fetch validation error messages when for example using the RequiredAttribute on a property. Can this be done?
我的问题是,我想使用我的自定义 ResourceManager 解决方案来获取验证错误消息,例如在属性上使用必需属性时。这能做到吗?
采纳答案by Darin Dimitrov
The RequiredAttributeallows to use a custom resource manager:
该RequiredAttribute标签允许使用一个自定义的资源管理器:
[Required(
ErrorMessageResourceType = typeof(CustomResourceManager),
ErrorMessageResourceName = "ResourceKey")]
public string Username { get; set; }
UPDATE:
更新:
Another possibility is to write your custom attribute:
另一种可能性是编写您的自定义属性:
public class CustomRequiredAttribute : RequiredAttribute
{
public override string FormatErrorMessage(string name)
{
return YourCustomResourceManager.GetResource(name);
}
}