ASP.NET MVC 2:数据 DataAnnotations 验证是约定
我有一个与资源一起使用的必需属性:
public class ArticleInput : InputBase
{
[Required(ErrorMessageResourceType = typeof(ArticleResources), ErrorMessageResourceName = "Body_Validation_Required")]
public string Body { get; set; }
}
我想按照惯例指定资源,如下所示:
public class ArticleInput : InputBase
{
[Required2]
public string Body { get; set; }
}
基本上,Required2
实现基于此数据的值:
ErrorMessageResourceType = typeof(ClassNameWithoutInput + Resources); // ArticleResources
ErrorMessageResourceName = typeof(PropertyName + "_Validation_Required"); // Body_Validation_Required
有没有办法实现这样的事情?也许我需要实现一个新的 ValidationAttribute。
I have a required attribute that used with resources:
public class ArticleInput : InputBase
{
[Required(ErrorMessageResourceType = typeof(ArticleResources), ErrorMessageResourceName = "Body_Validation_Required")]
public string Body { get; set; }
}
I want to specify the resources be convention, like this:
public class ArticleInput : InputBase
{
[Required2]
public string Body { get; set; }
}
Basically, Required2
implements the values based on this data:
ErrorMessageResourceType = typeof(ClassNameWithoutInput + Resources); // ArticleResources
ErrorMessageResourceName = typeof(PropertyName + "_Validation_Required"); // Body_Validation_Required
Is there any way to achieve something like this? maybe I need to implement a new ValidationAttribute
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为如果不为 attribute 提供自定义适配器,这是不可能的,或者至少不可能做到。您在属性的构造函数中没有任何方法来访问该属性所应用的方法/属性。如果没有它,您将无法获取类型或属性名称信息。
如果您为属性创建了一个适配器,然后将其注册到 DataAnnotationsModelValidatorProvider,那么在 GetClientValidationRules 中,您将可以访问 ControllerContext 和模型元数据。由此,您也许能够派生出正确的资源类型和名称,然后查找正确的错误消息并将其添加到属性的客户端验证规则中。
然后在global.asax.cs中
I don't think this is possible or, at least, not possible to do without also supplying a custom adapter for the attribute . You don't have any way in the constructor of the attribute to get access to the method/property that the attribute is applied to. Without that you can't get the type or property name information.
If you created an adapter for your attribute, then registered it with the DataAnnotationsModelValidatorProvider, then in the GetClientValidationRules, you would have access to the ControllerContext and model Metadata. From that you might be able to derive the correct resource type and name, then lookup the correct error message and add it to client validation rules for the attribute.
Then in global.asax.cs