Get encompassing class, then access a property of it inside custom attribute
I'm using ASP.NET MVC and implementing custom validation via custom attributes/data annotations on my models.
Is it possible to access a property on an object's parent class inside my custom attribute?
public class MyModel
{
[MyCustomValidator]
public string var1 {get; set;}
public string var2 {get; set;}
}
Note: Using asp.net mvc
public class MyCustomValidatorAttribute : ValidationAttribute
{
public bool override IsValid(Object value)
{
// somehow get access to var2 in the MyModel
}
}
So basically, making validation check another property for 开发者_JS百科a specific value. I tried to pass var2
's value as a parameter to MyCustomValidator
but that doesn't work.
No, basically. After a hunt through reflector, you only have access to the value of the member being tested - not the containing object or even the member-info of the property/field/whatever.
Which I agree is very limiting and frustrating, but it looks like this is fixed in 4.0 - my previous reply hinted at this, but in 4.0 there is an IsValid
overload that accepts a ValidationContext
, which provides this infomation via ObjectInstance
.
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
Just a note to say that you can do this with 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;
}
}
精彩评论