我正在使用 MVC 中的自定义验证来验证基于另一个字段的字段,我遇到了这个实现:
public class RequiredIfAttribute : ValidationAttribute
{
private String PropertyName { get; set; }
private String ErrorMessage { get; set; }
private Object DesiredValue { get; set; }
public RequiredIfAttribute(String propertyName, Object desiredvalue, String errormessage)
{
this.PropertyName = propertyName;
this.DesiredValue = desiredvalue;
this.ErrorMessage = errormessage;
}
protected override ValidationResult IsValid(object value, ValidationContext context)
{
Object instance = context.ObjectInstance;
Type type = instance.GetType();
Object proprtyvalue = type.GetProperty(PropertyName).GetValue(instance, null);
if (proprtyvalue.ToString() == DesiredValue.ToString())
{
return new ValidationResult(ErrorMessage);
}
return ValidationResult.Success;
}
}
我有一个简单的类定义如下:
public class Person
{
public int PersonID { get; set; }
public string name { set; get; }
[RequiredIf("name","","Address is required")]
public string addr { get; set; }
}
当我运行该页面时,我收到一个Object reference not set to an instance of an object.
错误,但更改该行以[RequiredIf("name","John","Address is required")]
产生预期的结果。我的问题是,您如何使用它来检查该字段是否为空。
我也尝试将行更改为,[RequiredIf("name",null,"Address is required")]
但我得到了同样的错误。