我想知道是否有一种方法可以在没有MVC站点的情况下使用ASP.NET的数据批注。
我的例子是,我有一个类,一旦创建就需要验证,否则就会抛出错误。我喜欢数据注释方法,而不是由初始化器触发的一堆if块。
有没有办法让它起作用呢?
我想应该是这样的:
在初始化程序中添加data annotations
有什么想法吗?我必须承认,我没有将MVC框架添加到我的项目中,因为我希望我可以只使用数据注解类System.ComponentModel.DataValidation。
发布于 2010-06-22 14:07:49
下面是一个例子:
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要强大得多。
https://stackoverflow.com/questions/3089760
复制相似问题