使用MVC的ASP.Net MVC数据注解之外 [英] Using ASP.Net MVC Data Annotation outside of MVC
问题描述
我想知道是否有使用ASP.Net的数据标注,而不MVC网站的一种方式。
i was wondering if there is a way to use ASP.Net's Data annotation without the MVC site.
我的例子是,我必须证实,曾经创造需求类,或将抛出一个错误。我喜欢数据注解的方法,而不是一堆if块由initaliser解雇的。
My example is that i have a class that once created needs to be validated, or will throw an error. I like the data annotations method, instead of a bunch of if blocks fired by the initaliser.
有没有办法得到这个工作?
Is there a way to get this to work?
我认为这将是这样的:
- 添加注释数据
- 火在初始化器的方法调用类上的MVC验证
什么想法?我必须承认我还没有加入MVC框架到我的项目作为我希望我可以只使用数据的注释类System.ComponentModel.DataValidation
any ideas? i must admit i havent added the MVC framework to my project as i was hoping i could just use the data annotations class System.ComponentModel.DataValidation
推荐答案
下面是一个例子:
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 是变得更加强大。
这篇关于使用MVC的ASP.Net MVC数据注解之外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!