MVC3:如何更改通用的[必填]验证消息文本? [英] MVC3: How to change the generic [Required] validation message text?

查看:71
本文介绍了MVC3:如何更改通用的[必填]验证消息文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用Required属性装饰模型对象的属性并且未指定ErrorMessageResourceType/Name时,您会收到插值形式为"{0}字段是必需的"的验证消息.参数0是该属性的DisplayName属性的值.

When you decorate a model object's property with the Required attribute and don't specify ErrorMessage or ResourceType/Name you get the validation message in the interpolated form of "The {0} field is required.", where param 0 is the value of the DisplayName attribute of that property.

我想将该默认字符串更改为其他名称,但我想保留其通用性质,也就是说,我不想为模型对象的每个属性指定ErrorMessageResourceType/Name.默认字符串存储在哪里,如何更改?

I want to change that default string to something else but I want to keep the generic nature of it, that is I don't want to specify ErrorMessage or ResourceType/Name for every property of the model object. Where is the default string stored and how can I change it?

推荐答案

派生自己的属性是一个不错的选择,开始时开销可能最低,但是您需要返回并更改所有现有的用法[Required].您(和您团队中的其他任何人)也将需要记住使用(并教新手使用)正确的前进方式.

Deriving your own attribute is a fair option and probably has the lowest overhead to get started, but you'll need to go back and change all your existing uses of [Required]. You (and any others on your team) will also need to remember to use (and teach newcomers to use) the right one going forward.

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

An alternative is to replace the ModelMetadataProviders and ModelValidatorProviders to return strings from a resource file. This avoids the drawbacks above. It also lays the groundwork for replacing messages for other attributes (e.g., MaxLengthAttribute) and for supporting additional languages.

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));
}

以下是完整的

Here is the full source, documentation, and a blog post describing the usage.

这篇关于MVC3:如何更改通用的[必填]验证消息文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆