I'm working on a button that calls an action in my asp.net mvc controller. I'm trying to catch errors and display them to the user in a decent way, but I can't seem to figure out how to do this properly. Whenever I force an exception (for testing purposes) in my controller, the .sucess part of my ajax call i still fired. Here's my ajax call:
$(document).ready(function() {
$("#del").on("click", function() {
var message;
$.ajax({
url: "@Url.Action("DeleteImage", "UnitSummary")",
type: "GET",
dataType: "json",
data: { unitId: "@Model.UnitId" },
error: function(msg) {
message = msg;
$('#delsection').hide().html('<div class="alert alert-danger"><strong>Ouch!</strong> ' + message.statusText + '</div>').fadeIn('slow');
},
success: function(msg) {
message = msg;
$('#delsection').hide().html('<div class="alert alert-success"><strong>Success!</strong> Image was deleted.</div>').fadeIn('slow');
}
});
});
And here's my controller:
[HttpGet]
public ActionResult DeleteImage(int unitId)
{
try
{
throw new Exception("Forced error");
UnitClient.UpdateUnitImage(unitId, new byte[0]);
}
catch (Exception e)
{
Log.Error(e);
return Json(new { e.Message }, JsonRequestBehavior.AllowGet);
}
return Json(new JsonResult(), JsonRequestBehavior.AllowGet);
}
Sucess always gets called, even though the image is not deleted. What am I missing here?
JsonResult. The result of the ajax call will always be200which is ok, that's why thesuccessmethod gets called.