Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/263.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# MVC3:如何更改通用[必需]验证消息文本?_C#_Asp.net Mvc 3_Data Annotations - Fatal编程技术网

C# MVC3:如何更改通用[必需]验证消息文本?

C# MVC3:如何更改通用[必需]验证消息文本?,c#,asp.net-mvc-3,data-annotations,C#,Asp.net Mvc 3,Data Annotations,当您使用Required属性装饰模型对象的属性,并且不指定ErrorMessage或ResourceType/Name时,您将获得插值形式的验证消息“需要{0}字段”。其中,参数0是该属性的DisplayName属性的值 我想将该默认字符串更改为其他字符串,但我想保留它的一般性质,即我不想为模型对象的每个属性指定ErrorMessage或ResourceType/Name。默认字符串存储在哪里?如何更改它?是否尝试创建RequiredAttribute的派生类并重写FormatErrorMess

当您使用
Required
属性装饰模型对象的属性,并且不指定
ErrorMessage
ResourceType/Name
时,您将获得插值形式的验证消息“需要{0}字段”。其中,参数0是该属性的
DisplayName
属性的值


我想将该默认字符串更改为其他字符串,但我想保留它的一般性质,即我不想为模型对象的每个属性指定
ErrorMessage
ResourceType/Name
。默认字符串存储在哪里?如何更改它?

是否尝试创建RequiredAttribute的派生类并重写FormatErrorMessage方法?这应该起作用:

public class MyRequiredAttribute : System.ComponentModel.DataAnnotations.RequiredAttribute
{
    public override string FormatErrorMessage(string name)
    {
        return base.FormatErrorMessage(string.Format("This is my error for {0}", name));
    }
}

派生您自己的属性是一个公平的选择,并且可能具有最低的开始开销,但是您需要返回并更改
[Required]
的所有现有用法。你(和你团队中的任何其他人)也需要记住在未来使用(并教新手使用)正确的方法

另一种方法是替换
modelmataproviders
modelvalidateproviders
以从资源文件返回字符串。这避免了上述缺点。它还为替换其他属性(例如,
MaxLengthAttribute
)的消息以及支持其他语言奠定了基础

protected void Application_Start()
{
    var stringProvider = new ResourceStringProvider(Resources.LocalizedStrings.ResourceManager);
    ModelMetadataProviders.Current = new LocalizedModelMetadataProvider(stringProvider);
    ModelValidatorProviders.Providers.Clear();
    ModelValidatorProviders.Providers.Add(new LocalizedModelValidatorProvider(stringProvider));
}

这是完整的,a描述了用法。

是的,但我应该阅读
MyRequiredAttribute
构造函数中的
DisplayName
元数据属性(而不是显式传递),因为我已经定义了/需要DisplayName。根据下面的链接,“name”参数是要包含在格式化消息中的名称。