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:

c# httpclient The remote certificate is invalid according to the validation procedure: RemoteCertificateNameMismatch

 If we get this error while trying to get http reponse using HttpClient object, it could mean that certificate validation fails for the remo...