Pet*_*ete 1 c# validation c#-4.0 asp.net-mvc-4
我正在尝试编写自己的验证属性,但是我无法从继承的类中获取属性的值.这是我的代码:
protected override ValidationResult IsValid(object value, ValidationContext context)
{
if (context.ObjectType.BaseType == typeof(AddressModel))
{
PropertyInfo property = context.ObjectType.BaseType.GetProperty(_propertyName);
// this is the line i'm having trouble with:
bool isRequired = (bool)property.GetValue(context.ObjectType.BaseType);
return base.IsValid(value, context);
}
return ValidationResult.Success;
}
Run Code Online (Sandbox Code Playgroud)
我不知道我的意思是什么,GetValue
因为它期待一个对象,但我传递的所有内容都给我一个属性类型与目标异常不匹配
我不得不转到基类型,因为我试图从继承的类中获取属性的值,并且context.ObjectInstance
不包含必要的属性
您可以简单地将对象转换为AddressModel
并使用它.
protected override ValidationResult IsValid(object value, ValidationContext context)
{
var addressModel = context.ObjectInstance as AddressModel
if (addressModel != null)
{
// Access addressModel.PROPERTY here
return base.IsValid(value, context);
}
return ValidationResult.Success;
}
Run Code Online (Sandbox Code Playgroud)
context.ObjectInstance
是object
类型而不是模型的类型,因为验证框架不是为了显式验证模型而创建的,而是正确的对象实例.一旦它被铸造,你可以正常使用它.
作为旁注,您遇到错误的原因property.GetValue(context.ObjectType.BaseType)
是因为该GetValue
方法需要您正在调用其属性的对象的实例.
归档时间: |
|
查看次数: |
3765 次 |
最近记录: |