0

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Or another option, a better one in my opinion, is to return a success flag (success = true in case of success), and use it in the success event of the ajax call, and use the error event only for unexpected errors.
Definitely. It is 100% inappropriate to both return a response body and 500 status.
@ChrisPratt According to W3C specification - there is nothing wrong for 500 status code response to have a body. See w3.org/Protocols/HTTP/HTRESP : "The body section may contain a document describing the error in human readable form."
within the above controller code, how would I implement the Response.StatusCode OR the success flag?
@dvs As I've already said it in the third paragraph of the answer. Just add Response.StatusCode = 500; before returning partial view.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.