在Windows窗体项目上使用DataAnnotations

时间:2010-01-21 13:18:54

标签: c# asp.net-mvc winforms c#-3.0 data-annotations

我最近使用ASP.Net MVC和DataAnnotations,并且正在考虑对Forms项目使用相同的方法,但我不确定如何去做。

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

更新:我使用了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)
        {

        }

您如何看待这种方法?

4 个答案:

答案 0 :(得分:21)

这是一个简单的例子。假设你有一个类似下面的对象

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上的参考:DataAnnotations Namespace

答案 1 :(得分:5)

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

答案 2 :(得分:0)

我发现了一个使用Validator类在WinForms中使用DataAnnotations的不错的示例,包括绑定到IDataErrorInfo接口,以便ErrorProvider可以显示结果。

这是链接。 DataAnnotations Validation Attributes in Windows Forms

答案 3 :(得分:-1)

如果您使用的是最新版本的Entity Framework,则可以使用此cmd获取错误列表(如果存在):

YourDbContext.Entity(YourEntity).GetValidationResult();