2013-02-22 139 views
1

我驗證基於使用自定義的驗證在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")],但我得到了同樣的錯誤。

回答

2

這似乎工作:

protected override ValidationResult IsValid(object value, ValidationContext context) 
     { 
      if (value != null) { return ValidationResult.Success; } 

      Object instance = context.ObjectInstance; 
      Type type = instance.GetType(); 
      Object proprtyvalue = type.GetProperty(PropertyName).GetValue(instance, null); 
      if (proprtyvalue == null) { 
       return new ValidationResult(ErrorMessage); 
      } 
      return ValidationResult.Success; 
     } 
0

你沒有張貼你正在測試的實際實例化的人,所以我只是猜測:確保屬性名的proprtyvalue是不是要調用toString()就可以了之前空。所以,你的Person.Name不能