简体   繁体   English

在 MVC 之外使用 ASP.Net MVC 数据注释

[英]Using ASP.Net MVC Data Annotation outside of MVC

i was wondering if there is a way to use ASP.Net's Data annotation without the MVC site.我想知道是否有一种方法可以在没有 MVC 站点的情况下使用 ASP.Net 的数据注释。

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.我喜欢数据注释方法,而不是初始化程序触发的一堆 if 块。

Is there a way to get this to work?有没有办法让它发挥作用?

I thought it would be something like:我认为它会是这样的:

  • Add data annotations添加数据注释
  • Fire a method in the initialiser that calls the MVC validator on the class在初始化程序中触发一个方法,该方法在类上调用 MVC 验证器

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我必须承认我还没有将 MVC 框架添加到我的项目中,因为我希望我可以只使用数据注释类 System.ComponentModel.DataValidation

Here's an example:下面是一个例子:

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);
            }
        }
    }
}

But quite honestly FluentValidation is much more powerful.但老实说, FluentValidation 的功能要强大得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM