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:
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
ComponentModel. DataAnnotations Namespace. Provides attribute classes that are used to define metadata for ASP.NET MVC and ASP.NET data controls.
In Asp.net MVC, we can easily apply validation to web application by using Data Annotation attribute classes to model class. Data Annotation attribute classes are present in System.
In ASP.NET MVC application we can do the Server Side Validation on the Model using Data Annotations. Data Annotations is a namespace that provides attribute classes, and these classes define metadata for controls. In MVC we decorate Model Properties with these attribute classes to provide metadata.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With