这是一种无需子类化的方法RequiredAttribute
。只需制作一些属性适配器类。这里我使用ErrorMessageResourceType
/ ErrorMessageResourceName
(带有资源),但您可以轻松设置ErrorMessage
,甚至在设置这些覆盖之前检查是否存在覆盖。
全球.asax.cs:
public class MvcApplication : HttpApplication {
protected void Application_Start() {
// other stuff here ...
DataAnnotationsModelValidatorProvider.RegisterAdapter(
typeof(RequiredAttribute), typeof(CustomRequiredAttributeAdapter));
DataAnnotationsModelValidatorProvider.RegisterAdapter(
typeof(StringLengthAttribute), typeof(CustomStringLengthAttributeAdapter));
}
}
private class CustomRequiredAttributeAdapter : RequiredAttributeAdapter {
public CustomRequiredAttributeAdapter(ModelMetadata metadata, ControllerContext context, RequiredAttribute attribute)
: base(metadata, context, attribute)
{
attribute.ErrorMessageResourceType = typeof(Resources);
attribute.ErrorMessageResourceName = "ValRequired";
}
}
private class CustomStringLengthAttributeAdapter : StringLengthAttributeAdapter {
public CustomStringLengthAttributeAdapter(ModelMetadata metadata, ControllerContext context, StringLengthAttribute attribute)
: base(metadata, context, attribute)
{
attribute.ErrorMessageResourceType = typeof(Resources);
attribute.ErrorMessageResourceName = "ValStringLength";
}
}
此示例将让您创建一个名为 Resources.resx 的资源文件,其中ValRequired
包含新的必需默认消息和ValStringLength
超出默认消息的字符串长度。请注意,对于两者,{0}
都会收到字段的名称,您可以使用[Display(Name = "Field Name")]
.