【问题标题】:How to use DataAnnotations ErrorMessageResourceName with custom Resource Solution如何将 DataAnnotations ErrorMessageResourceName 与自定义资源解决方案一起使用
【发布时间】:2011-01-21 19:17:03
【问题描述】:

我正在使用 C# 构建一个 MVC Web 应用程序。由于该站点将是多语言的,因此我实现了自己的 ResourceManager。此类负责根据当前线程文化从数据库/缓存中获取所需的资源字符串,并且到目前为止工作正常。

我的问题是,例如在属性上使用 Required 属性时,我想使用我的自定义 ResourceManager 解决方案来获取验证错误消息。这个可以吗?

【问题讨论】:

    标签: c# asp.net-mvc validation resources data-annotations


    【解决方案1】:

    RequiredAttribute 允许使用custom resource manager

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

    更新:

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

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

    【讨论】:

    • 我的 ResourceManager 是一个真正的自定义解决方案,它既没有以任何方式连接到 MVC,也没有实现除我创建的接口之外的任何接口。需要进行哪些更改才能以这种方式使用我的 ResourceHandler?
    • 是否还需要其他任何东西才能使自定义属性起作用?我已经尝试过了,它似乎不起作用。我是否需要创建自己的 EditorFor 扩展方法来使用新的属性类型?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-02
    • 2017-09-27
    • 2013-06-09
    • 2018-11-26
    相关资源
    最近更新 更多