C# 如何覆盖默认的必需错误消息

C# 如何覆盖默认的必需错误消息,c#,asp.net-mvc,asp.net-mvc-2,data-annotations,C#,Asp.net Mvc,Asp.net Mvc 2,Data Annotations,我有一个旧的C#MVC2.0 web应用程序 每当我使用[Required]属性时,默认的验证错误消息如下: [where]字段是必需的 我的问题是应用程序不是英语的,所以我基本上必须将属性调用更改为[必需(ErrorMessage=“Le champ[which]est requires.”] 是否有方法覆盖默认错误消息,以便我只需要在需要特定消息时指定它 我要找的东西是: DefaultRequiredMessage = "Le champ {0} est requis."; 您可以创建一

我有一个旧的C#MVC2.0 web应用程序

每当我使用
[Required]
属性时,默认的验证错误消息如下:

[where]字段是必需的

我的问题是应用程序不是英语的,所以我基本上必须将属性调用更改为
[必需(ErrorMessage=“Le champ[which]est requires.”]

是否有方法覆盖默认错误消息,以便我只需要在需要特定消息时指定它

我要找的东西是:

DefaultRequiredMessage = "Le champ {0} est requis.";

您可以创建一个类并从中继承它。大概是这样的:

public class CustomRequired: RequiredAttribute
{
    public CustomRequired()
    {
        this.ErrorMessage = "Le champ est requis.";
    }
}
或:


您应该在属性中使用
CustomRequired
,而不是
[必需]

请执行以下操作以覆盖默认的必需错误消息:

  • 创建一个自定义适配器,继承RequiredAttributeAdapter,如下所示:


  • 资源文件配置:

我不明白,你对
[必需(ErrorMessage=“MyNotEnglishMessage”)]有什么问题?
我不想在我的应用程序中到处写同样的消息,我想遵循枯燥的原则。你能不能不安装法语语言包并将CurrentUICulture设置为法语文化(例如fr或fr)?或者,如果您不想安装语言包,请使用自定义资源管理器:@Joe这是一个非常旧的应用程序,所以我甚至不知道是否可以找到法语语言包,如果它与所需的语言包不完全匹配,我真的不想冒险把所有东西都搞砸。我认为S.Akbari的解决方案接近你的第二个选择,所以我宁愿看看这是否如预期的那样有效,因为它几乎没有机会把事情搞砸。然而,我同意有一个法语语言包将是一个伟大的解决方案!如何将其更改为在错误消息中包含字段名?它不应该是
CustomRequiredAttribute
而不是
CustomRequired
?无论如何,谢谢你,让我试试看,如果它像预期的那样工作,我会接受这个answer@Rafalon它只是自定义类的名称。可以随意给它命名:)是的,我只是觉得它应该以
属性
结尾,这样我们就可以使用
[CustomRequired]
public class CustomRequired: RequiredAttribute
{
    public override string FormatErrorMessage(string whatever)
    {
        return !String.IsNullOrEmpty(ErrorMessage)
            ? ErrorMessage
            : $"Le champ {whatever} est requis.";
    }
}
public class YourRequiredAttributeAdapter : DataAnnotationsModelValidator<RequiredAttribute>
{
    public YourRequiredAttributeAdapter(ModelMetadata metadata, ControllerContext context, RequiredAttribute attribute)
        : base(metadata, context, attribute)
    {
        if (string.IsNullOrWhiteSpace(attribute.ErrorMessage)
            )
        {
            attribute.ErrorMessageResourceType ="Your resource file";
            attribute.ErrorMessageResourceName = "Keep the key name in resource file as "PropertyValueRequired";
        }
    }

}
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredAttribute), typeof(YourRequiredAttributeAdapter));