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?
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);
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