我想知道是否有办法在没有MVC网站的情况下使用ASP.Net的数据注释。
我的例子是我有一个曾经创建过的类需要验证,否则会抛出错误。我喜欢数据注释方法,而不是initaliser发出的一堆if块。
有没有办法让它发挥作用?
我认为它会是这样的:
任何想法?我必须承认我还没有将MVC框架添加到我的项目中,因为我希望我可以使用数据注释类System.ComponentModel.DataValidation
答案 0 :(得分:29)
以下是一个例子:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public class Foo
{
[Required(ErrorMessage = "the Bar is absolutely required :-)")]
public string Bar { get; set; }
}
class Program
{
public static void Main()
{
var foo = new Foo();
var results = new List<ValidationResult>();
var context = new ValidationContext(foo, null, null);
if (!Validator.TryValidateObject(foo, context, results))
{
foreach (var error in results)
{
Console.WriteLine(error.ErrorMessage);
}
}
}
}
但老实说FluentValidation更强大。