Reputation: 1
I am making an ajax call to the controller. The controller will return a string if the execution is successful or it will return a partial view if an error is found. I am forcing it to fail, but it still goes into the success event in the ajax.
How do I go about getting it to display the partial view when failed OR just alert the string value when successful?
Ajax call:
$.ajax({
url: '@Url.Action("GetItem","Home")',
data: { },
success: function (result) {
alert(result);
},
error: function (result) {
$(".MyDiv").html(result);
}
})
Controller:
public ActionResult GetItem([DataSourceRequest]DataSourceRequest request)
{
try
{
throw new Exception("ERROR");
//return Json("Success", JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
AlertMessage alertMessage = new AlertMessage();
alertMessage.MessageText = "A critical error has occurred, please contact your administrator.";
alertMessage.ErrorMessageText = ex.ToString();
alertMessage.MessageHeading = "Critical Error";
return PartialView("~/Views/Common/ErrorMessageDisplay.cshtml", alertMessage);
}
}
Upvotes: 0
Views: 1247
Reputation: 26846
Function you've provided as error
argument of ajax call will be called if the request fails. This means response status code is one of 40* or 50* codes.
But when you're returning PartialView
from your controller, actually response has status code 200 that is "OK" - that's why success function is being called.
You can modify your controller code by adding Response.StatusCode = 500;
just before return PartialView(...
, and this should do the trick.
Upvotes: 1