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

时间:2021-12-14 16:39:30

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.

我的例子是我有一个曾经创建过的类需要验证,否则会抛出错误。我喜欢数据注释方法,而不是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

1 个解决方案

#1


28  

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功能更强大。

#1


28  

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功能更强大。