使用App_GlobalResources目录中的resx文件,我已经能够更改模型验证器的PropertyValueInvalid字符串的默认消息.
但是当需要值时,它无法转换消息(PropertyValueRequired.)
在Global.asax.cs Application_Start()中,我更改了资源类键,如下所示:
DefaultModelBinder.ResourceClassKey = "Messages";
在Messages.resx文件中,我放了两个条目:
"PropertyValueInvalid"=>"O valor'{0}'éinválidoparao campo {1}."
"PropertyValueRequired"=>"Éadmandáriigiditaro {0}."
谢谢.
RequiredAttribute未使用DefaultModelBinder.GetValueRequiredResource.创建自定义DataAnnotationsModelValidator类.
public class MyRequiredAttributeAdapter : RequiredAttributeAdapter { public MyRequiredAttributeAdapter(ModelMetadata metadata, ControllerContext context, RequiredAttribute attribute) : base(metadata, context, attribute) { attribute.ErrorMessageResourceType = typeof (Messages); attribute.ErrorMessageResourceName = "PropertyValueRequired"; } }
并在Global.asax中注册适配器.
DataAnnotationsModelValidatorProvider.RegisterAdapter( typeof(RequiredAttribute), typeof(MyRequiredAttributeAdapter));
希望这有帮助!
DataAnnotations的可重用验证错误消息资源字符串
此消息将被绑定到System.ComponentModel.DataAnnotations
密钥下的程序集中RequiredAttribute_ValidationError
.您可以编写自定义验证属性:
public class MyRequiredAttribute : RequiredAttribute { public MyRequiredAttribute() { ErrorMessageResourceType = typeof(Messages); ErrorMessageResourceName = "Required"; } }
然后在你的Messages.resx
文件中定义Required
字符串:
Required => É necessário digitar o {0}.
最后用这个自定义属性装饰你的视图模型属性:
public class MyViewModel { [MyRequired] public int Foo { get; set; } }