I have Action Method of types "JsonResult". I call it using ajax post. I want to return the custom errors from the action method back to ajax post and display those errors as validation Summary.
[HttpPost]
public JsonResult RegisterUser(RegistrationModel model)
{
//if username already exists return custom error to be displayed on view
//under validation summary
// control should go back to error function with message to be displayed.
}
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
data: ko.toJSON(model),
contentType: "application/json; charset=utf-8",
success: function (result) {
success(result)
},
error: function (req, status, error) {
error(req, status, error);
}
});
function success(result) {
//Do Something
}
function error(req, status, error) {
//Display error messages under validation summary.
}
From my understanding, when you do an ajax post, it doesn't care if the Model Validation passed or not, it only cares if it got a response from the server. If an Exception gets thrown from the server, then it will hit your ajax error function.
So what I would do is return a json object that lets me know the validation status.
if(!ModelState.IsValid){
var modelStateErrors = this.ModelState.Keys.SelectMany(key => this.ModelState[key].Errors);
var message = "Please fix the following: " + Environment.NewLine;
foreach (var modelStateError in modelStateErrors)
{
message += modelStateError.ErrorMessage + Environment.NewLine;
}
return Json(new {success = false, response = message})
}
// Do other logic
return Json(new {success = true, response = "Successful message"})
Once you pass this object back, you can do the following Javascript
success: function (result) {
if(result.success === true){
$('#status-div').empty().html('<div class="success">' + result.response + '</div>');
}
if(result.success === false){
$('#status-div').empty().html('<div class="fail">' + result.response + '</div>');
}
}