Friday, November 15, 2019

MVC validate a model using data annotation attributes without model binding

Sometimes, we need to validate a data model without model binding. For example, if the application has separate models for the actual data entity and an action method such as edit action in a view. In such cases, it would be very convenient to use data annotation attributes already specified on the model to perform validation logic.


This can be achieved by using ValidationContext and Validator objects, like so:


 var widget = new Widget
                        {
                            Id = 12,
                            Price = 15.57M
                        };

        var context = new ValidationContext(widget, null, null);
        var results = new List<ValidationResult>();
        if( Validator.TryValidateObject( widget, context, results, true ) )
        {
            //Validation Successful
        }
        else
        {
            //Validation Failed
        }


More information can be found at https://stackoverflow.com/questions/7101800/can-i-check-modelstate-without-modelbinding

No comments:

SSL Error - The connection for this site is not secure

 After cloning a git repo of dot net framework website and trying to run it all I could see was this error Turns out the fix was to simply e...