我驗證基於使用自定義的驗證在MVC另一個字段的字段,我碰到這個實施傳來:requiredif實體框架空場
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")]
,但我得到了同樣的錯誤。