本地化 mvc 3.0 验证客户端消息
首先对 Microsoft MVC 团队感到抱歉,因为没有用于本地化数据注释验证消息的简单解决方案。我花了很多时间,最后没有找到简单的解决方案!
我最终决定继承RequiredAttribute
来进行本地化。所以我这样做了:
public class MyRequiredAttribute : System.ComponentModel.DataAnnotations.RequiredAttribute
{
public MyRequiredAttribute()
: base()
{
this.ErrorMessageResourceType = typeof(Resources.DataAnnotationDefaults);
this.ErrorMessageResourceName = "Required";
}
}
我在 DataAnnotationDefaults.resx 文件中提供了本地化消息。 所以我可以简单地使用它
[MyRequired]
public int UnitCode { get; set; }
,但问题是:它不适用于客户端,仅适用于服务器端。为什么?我错过了什么?
令人惊奇的是,下面的代码行没问题,并且在客户端也可以工作!
[Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(DataAnnotationDefaults))]
public int UnitCode { get; set; }
如果有人能在这方面帮助我,我将感到高兴和感激。
At first sorry for Microsoft MVC team because of no simple solution for localizing data annotation validation messages. It takes me a lot of time and finally no simple solution found!
I finally decided to inherit from RequiredAttribute
to do localization. so I did this :
public class MyRequiredAttribute : System.ComponentModel.DataAnnotations.RequiredAttribute
{
public MyRequiredAttribute()
: base()
{
this.ErrorMessageResourceType = typeof(Resources.DataAnnotationDefaults);
this.ErrorMessageResourceName = "Required";
}
}
where I provided my localized messages in DataAnnotationDefaults.resx
file.
So I can use this simply
[MyRequired]
public int UnitCode { get; set; }
But the problem is: it doesn't apply in client-side and just in server-side. why? what did I miss?
It is amazing that the following line is ok and works in client-side too!
[Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(DataAnnotationDefaults))]
public int UnitCode { get; set; }
I will be glad and appreciated if someone can help me on this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要了解验证在 MVC 和 .NET 中的工作原理。 DataAnnotation 是一个通用验证库,可用于各种应用程序而不仅仅是 MVC。
因此,MVC 包含不同类型的 MVC 适配器,用于添加对 DataAnnotations 的支持。客户端适配器是专门为 System.ComponentModel.DataAnnotations 中定义的属性而设计的。
因此,您需要创建自己的适配器以使其与您的派生属性一起使用。我写了一个 博客条目。
更简单的方法是使用我的 本地化元数据提供程序。
You need to understand how validation works in MVC and .NET. DataAnnotation is a generic validation library which can be used in all kinds of applications and not just MVC.
Hence MVC contains different types of adapters for MVC which is used to add support for DataAnnotations. The client-side adapters are specifically made for the attributes defined in
System.ComponentModel.DataAnnotations
.You therefore need to create your own adapters to get it working with your derived attributes. I've written a blog entry about it.
The easier approach is to use my localized metadata provider.