gpt4 book ai didi

c# - 在 Windows 窗体项目上使用 DataAnnotations

转载 作者:可可西里 更新时间:2023-11-01 02:59:24 24 4
gpt4 key购买 nike

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

}

您如何看待这种方法?

最佳答案

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

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

关于c# - 在 Windows 窗体项目上使用 DataAnnotations,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2109423/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com