开发者

Validating data annotations inside a class: TryValidateObject results always empty

I'm currently migrating my .NET 3.5 code to .NET 4.0, where I had implemented my own validation logic. Using data annotations to validate data, seems very apealing, I just can't get it to work tough..

Below is an simplified example, of what I'm trying to achieve. The result collection passed to the TryValidateObject always has count of 0.

What am I doing wrong?

public class CreateBuskerMemberCommand : Command
{
   [Required]
   public string SomeValue;

   public开发者_运维技巧 string SomeOtherValue;

   public CreateBuskerMemberCommand ( ..)
   {
      // pass values to fields.. 
   }


   public void Execute()
   {

       // force error for testing purpose
       SomeValue = null;
       ValidationContext context = new ValidationContext(this, null, null);
       List<ValidationResult> results = new List<ValidationResult>();

       System.ComponentModel.DataAnnotations.Validator.TryValidateObject(this, context,   results);

      // results count = 0
   }
}


Very simple solution: The attributes have to be on a property and not a field. This did the trick

   [Required]
   public string SomeValue {get;set;}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜