我遇到了一个场景,我需要知道当前正在验证哪个属性在一个习惯中ValidationAttribute
。我认为这在 MVC 3 中会很容易,因为ValidationContext
正在被传递到IsValid http://msdn.microsoft.com/en-us/library/dd730022%28v=VS.100%29.aspx method.
无需详细说明,以下是基本思想:
protected override ValidationResult IsValid(Object value, ValidationContext validationContext) {
if (ShouldICareAboutYou(validationContext.MemberName))
{
//Do some stuff
}
//Return the results
}
这似乎是完美的解决方案,事实上,当使用单元测试我的自定义 ValidationAttribute 时Validator.TryValidateObject http://msdn.microsoft.com/en-us/library/dd411772%28v=vs.95%29.aspx一切都很顺利!
然而...
打电话时TryUpdateModel http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.tryupdatemodel.aspx, or TryValidateModel http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.tryvalidatemodel.aspx在我的控制器中,验证运行,但是ValidationContext.MemberName
一片空白。
哇哈?!?
我做了一些调查,果然,就在里面DataAnnotationsModelValidator http://msdn.microsoft.com/en-us/library/system.web.mvc.dataannotationsmodelvalidator.aspx是代码...还是缺少代码。
public override IEnumerable<ModelValidationResult> Validate(object container) {
// Per the WCF RIA Services team, instance can never be null (if you have
// no parent, you pass yourself for the "instance" parameter).
ValidationContext context = new ValidationContext(container ?? Metadata.Model, null, null);
context.DisplayName = Metadata.GetDisplayName();
// Setting the MemberName here would be trivial!
// However, philh told me not to. Something about
// a guy named Josh who pushed him down on the playground
// in middle school.
//context.MemberName = Metadata.PropertyName; (Suck It, Josh!!!)
ValidationResult result = Attribute.GetValidationResult(Metadata.Model, context);
if (result != ValidationResult.Success) {
yield return new ModelValidationResult {
Message = result.ErrorMessage
};
}
}
我意识到DisplayName
could如果没有则为属性名称DisplayAttribute
已应用于该物业。不幸的是我不能真正处理假设。我需要知道exactly属性名称是什么。
那么到底是怎么回事呢?这是有意为之还是出于诚实的疏忽。如果这是一个疏忽,那么在 MVC 4 中修复这个问题就太棒了:)
免责声明:
The added上面代码示例中的注释是为了搞笑。我不知道,也没有遇见过菲尔·哈克 http://haacked.com/articles/AboutHaacked.aspx。据我所知,他看起来是一个非常好的人。如果在中学时把他推倒的话,我就会成为一个皇家混蛋!