Using ASP.Net MVC Data Annotation outside of MVC

心已入冬 提交于 2019-11-30 08:00:26

问题


i was wondering if there is a way to use ASP.Net's Data annotation without the MVC site.

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?

I thought it would be something like:

  • Add data annotations
  • Fire a method in the initialiser that calls the MVC validator on the class

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


回答1:


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.



来源:https://stackoverflow.com/questions/3089760/using-asp-net-mvc-data-annotation-outside-of-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!