Jason King Team : Web Development Tags : Web Development

Return MVC model state errors via AJAX

Jason King Team : Web Development Tags : Web Development

How often do you see this type of JavaScript AJAX call?

 

$.ajax({
	url: "/controller/action",
	data: data,
	contentType: 'application/json',
	dataType: 'json',
	type: "post",
	success: function (response) {
		if (response.success) {
	// do something clever
		} else {
			alert('An error occurred, please try again.');
		}
	}
});

 

As you can see the code doesn’t tell the user why an error occurred and what they might be able to do to correct it.

To improve this you could return the model state errors from the action and display them to the user:

[HttpPost]
public JsonResult Edit(EditModel model)
{
      if (!ModelState.IsValid)
      {
            return Json(new { success = false, issue = model, errors = ModelState.Values.Where(i => i.Errors.Count > 0) });
       }

       // perform save
}

 

Read the errors from the AJAX response:

for (var i = 0; i < response.errors.length; i++) {
      var error = ko.mapping.fromJS(response.errors[i]);
      self.saveErrors.push(error);
}

Note that self.saveErrors is an observable array which is cleared before the AJAX call.

 

Display them in the View:

<div class="td" data-bind="visible: saveErrors().length > 0">
<p><strong>An error occured whilst trying to save this issue.</strong></p>
<ul data-bind="foreach: saveErrors()">
<!-- ko foreach: errors() -->
<li data-bind="text: errorMessage"></li>
<!-- /ko -->
</ul>
</div>