Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

See the Validation Summary in the controller

I have a strongly-typed ajax call (POST) in one of my MVC pages. I don't want to try and wire up client-side validation for that, and there will be no summaries to display on the client side, however, I'd like to throw some data annotations on the model and validate on the controller; if it fails validation I'd like to send back what would have been in the validation summary as a JSON property so I can show it in a dialog box as an error message.

How can I provide the JsonResponse the text of the validation summary in my controller?

like image 463
Jeremy Holovacs Avatar asked Oct 17 '11 23:10

Jeremy Holovacs


1 Answers

If you are trying to obtain the errors, you would simply use ModelState.Errors to obtain all of the errors from your controller. From there you can craft the JSON response any way you'd like:

var response = new
                    {
                        isValid = ModelState.IsValid,
                        errors = ModelState
                        .SelectMany(ms => ms.Value.Errors)
                        .Select(ms => ms.ErrorMessage)
                    };
return Json(response);
like image 116
vcsjones Avatar answered Oct 17 '22 17:10

vcsjones