【问题标题】:Using DataAnnotations on Windows Forms project在 Windows 窗体项目上使用 DataAnnotations
【发布时间】:2010-01-21 13:18:53
【问题描述】:

我最近将 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)
        {

        }

您如何看待这种方法?

【问题讨论】:

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


    【解决方案1】:

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

    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 框架,因此您可以在不同类型的应用程序中使用它。上面的代码sn-p返回true,尝试更新属性值得到验证错误。

    请务必查看 MSDN 上的参考资料:DataAnnotations Namespace

    【讨论】:

    • 你摇滚!..这是问题的真正答案!..非常感谢...
    【解决方案2】:

    Steve 的示例有点过时(尽管仍然不错)。他拥有的 DataAnnotationsValidationRunner 现在可以替换为 System.ComponentModel.DataAnnotations.Validator 类,它具有用于验证已用 DataAnnotations 属性修饰的属性和对象的静态方法。

    【讨论】:

    • 在 MVC 之外使用这个 Validator 类的例子并不多,所以你可能想用这样的方式来调用它:var results = new List&lt;ValidationResult&gt;(); var success = Validator.TryValidateObject(thing, new ValidationContext(thing, null, null), results);
    • 另请注意,如果您使用的是[Range],则必须在results 方法中的results 之后添加true
    【解决方案3】:

    我发现了一个使用 Validator 类将 DataAnnotations 与 WinForms 结合使用的体面示例,包括绑定到 IDataErrorInfo 接口,以便 ErrorProvider 可以显示结果。

    这是链接。 DataAnnotations Validation Attributes in Windows Forms

    【讨论】:

      【解决方案4】:

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

      YourDbContext.Entity(YourEntity).GetValidationResult();
      

      【讨论】:

        猜你喜欢
        • 2015-11-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-10
        • 1970-01-01
        • 2011-10-30
        • 2015-01-18
        相关资源
        最近更新 更多