Dou*_*oug 20 c# asp.net-mvc class-library data-annotations
我想知道是否有一种方法可以在没有MVC网站的情况下使用ASP.Net的数据注释.
我的例子是我有一个曾经创建过的类需要验证,否则会抛出错误.我喜欢数据注释方法,而不是initaliser发出的一堆if块.
有没有办法让这个工作?
我以为它会是这样的:
有任何想法吗?我必须承认我没有将MVC框架添加到我的项目中,因为我希望我可以使用数据注释类System.ComponentModel.DataValidation
Dar*_*rov 30
这是一个例子:
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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
但说实话,FluentValidation更强大.