Using Data Annotations in a Web Forms Project

When I use the component model data annotation attributes outside the context of the MVC environment (inside the web forms web project), can I then call the inline process to validate the annotated data and get the results?

The IValidatableObject interface provides a validation mechanism, but I still need a hook for this process to retrieve the ValidationResult s. This is what I am looking for.

+3


source to share


1 answer


I came up with the following working sample for validating annotations from within my website project.

If anyone knows a better way, feel free to share your answer.



using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;


// This method is on the same class that has been annotated with data attributes.
// That why the validation logic references 'this'.
// 
public override void Validate()
{
    ValidationContext context = new ValidationContext(this, null, null);
    List<ValidationResult> results = new List<ValidationResult>();
    Validator.TryValidateObject(this, context, results, true);
    if (results.Any()) // do whatever you want with the results.
        throw new Exception("validation failed");

}

      

+1


source







All Articles