2010-01-21 57 views
12

我最近使用了带有DataAnnotations的ASP.Net MVC,并且正在考虑对Forms项目使用相同的方法,但我不确定如何去解决它。在Windows窗体项目上使用DataAnnotations

我已经设置了我的属性,但是当我点击保存时他们似乎没有被检查。

更新:我已经使用Steve Sanderson's approach将检查我的类属性,并返回错误的集合,像这样:

 try 
     { 
      Business b = new Business(); 
      b.Name = "feds"; 
      b.Description = "DFdsS"; 
      b.CategoryID = 1; 
      b.CountryID = 2; 
      b.EMail = "SSDF"; 
      var errors = DataAnnotationsValidationRunner.GetErrors(b); 
      if (errors.Any()) 
       throw new RulesException(errors); 

      b.Save(); 
     } 
     catch(Exception ex) 
     { 

     } 

你觉得这个办法怎么样?

回答

6

史蒂夫的例子​​有点过时(虽然仍然很好)。他拥有的DataAnnotationsValidationRunner现在可以被System.ComponentModel.DataAnnotations.Validator类替换,它具有用于验证已使用DataAnnotations属性修饰的属性和对象的静态方法。

+3

这里没有在MVC之外使用这个'Validator'类的例子很多,所以你可能想用这样的方式调用它:'var results = new List (); var success = Validator.TryValidateObject(thing,new ValidationContext(thing,null,null),results);' – 2012-12-19 23:00:57

+0

另请注意,如果您使用'[Range]',则必须在'results'后添加'true'在TryValidateObject方法中。 – Stephen 2014-01-17 15:07:42

18

下面是一个简单的例子。假设你有一个像下面

using System.ComponentModel.DataAnnotations; 

public class Contact 
{ 
    [Required(AllowEmptyStrings = false, ErrorMessage = "First name is required")] 
    [StringLength(20, MinimumLength = 5, ErrorMessage = "First name must be between 5 and 20 characters")] 
    public string FirstName { get; set; } 

    public string LastName { get; set; } 

    [DataType(DataType.DateTime)] 
    public DateTime Birthday { get; set; } 
} 

一个对象,假设我们有一个创建这个类的一个实例,并试图验证其性能的方法,下面

private void DoSomething() 
    { 
     Contact contact = new Contact { FirstName = "Armin", LastName = "Zia", Birthday = new DateTime(1988, 04, 20) }; 

     ValidationContext context = new ValidationContext(contact, null, null); 
     IList<ValidationResult> errors = new List<ValidationResult>(); 

     if (!Validator.TryValidateObject(contact, context, errors,true)) 
     { 
      foreach (ValidationResult result in errors) 
       MessageBox.Show(result.ErrorMessage); 
     } 
     else 
      MessageBox.Show("Validated"); 
    } 

所列的DataAnnotations命名空间不绑定到MVC框架,以便您可以在不同类型的应用程序中使用它。上面的代码片段返回true,尝试更新属性值以获取验证错误。

并确保签MSDN上的参考:如果您使用实体框架的最新版本中,你可以使用这个cmd以得到你的错误列表,如果现有DataAnnotations Namespace

0

YourDbContext.Entity(YourEntity).GetValidationResult(); 
相关问题