3

我正在使用 ASP.NET MVC 并通过模型上的自定义属性/数据注释实现自定义验证。

是否可以在我的自定义属性中访问对象父类的属性?

public class MyModel
{
    [MyCustomValidator]
    public string var1 {get; set;}
    public string var2 {get; set;}
}

注意:使用 asp.net mvc

public class MyCustomValidatorAttribute : ValidationAttribute
{
    public bool override IsValid(Object value)
    {  
          // somehow get access to var2 in the MyModel
    }
}

所以基本上,使验证检查另一个属性的特定值。我试图将var2's 的值作为参数传递给,MyCustomValidator但这不起作用。

4

3 回答 3

3

不,基本上。在通过反射器搜索之后,您只能访问被测试成员的- 而不是包含对象,甚至是属性/字段/其他内容的成员信息。

我同意这是非常有限和令人沮丧的,但看起来这在 4.0 中已修复 - 我之前的回复暗示了这一点,但在 4.0 中有一个IsValid接受 a 的重载ValidationContext,它通过ObjectInstance.

于 2010-01-23T08:50:25.253 回答
1

Apparently, MVC 2 Validation doesn't support validationContext because MVC 2 targets DA 3.5. I'm not sure if this is still the case with MVC 2 RC, I'm using VS 2010 with MVC 2 Preview 1.

Taken from Brad Wilson's post at http://forums.asp.net/p/1457591/3650720.aspx

There is no validation context in the 3.5 SP1 version of DataAnnotations, which is what MVC 2 targets. The [CustomValidation] attribute is also an artifact of DA4.0, so to write a custom validation, you need to create a new validation attribute derived from ValidationAttribute

于 2010-01-31T05:37:57.977 回答
0

只是说明您可以使用 MVC3 执行此操作:

public class MyCustomValidatorAttribute : ValidationAttribute
{
    public bool override IsValid(Object value)
    {  
          var model = validationContext.ObjectInstance as MyModel; 
          // would probably use reflection and pass property names instead of casting in real life

          if (model.var2 != null && value == null)
          {
            return new ValidationResult("var1 is required when var2 is set");
          }

          return ValidationResult.Success;
    }
}
于 2010-11-24T14:56:22.993 回答