在Windows窗体项目上使用DataAnnotations

Jon*_*Jon 17 c# asp.net-mvc winforms data-annotations c#-3.0

我最近使用ASP.Net MVC和DataAnnotations,并考虑使用相同的方法进行Forms项目,但我不知道如何去做.

我已经设置了我的属性,但是当我单击"保存"时似乎没有检查它们.

更新:我使用了Steve Sanderson的方法来检查我的类的属性并返回一组错误,如下所示:

        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)
        {

        }
Run Code Online (Sandbox Code Playgroud)

您如何看待这种方法?

Nex*_*xus 22

这是一个简单的例子.假设你有一个像下面这样的对象

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; }
}
Run Code Online (Sandbox Code Playgroud)

假设我们有一个方法可以创建此类的实例并尝试验证其属性,如下所示

    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");
    }
Run Code Online (Sandbox Code Playgroud)

DataAnnotations命名空间与MVC框架无关,因此您可以在不同类型的应用程序中使用它.上面的代码片段返回true,尝试更新属性值以获取验证错误.

并确保签出MSDN上的引用:DataAnnotations命名空间

  • 你太棒了!.. **这是问题的真正答案!..** 非常感谢...... (2认同)

Pau*_*aul 5

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

  • 在MVC之外没有大量使用这个`Validator`类的例子,所以你可能想用这样的东西来调用它:`var results = new List <ValidationResult>(); var success = Validator.TryValidateObject(thing,new ValidationContext(thing,null,null),results);` (3认同)