-2

I've never understood: What determines whether the success or error function of

$.ajax( { ...,
          success : function ( retobj ) { ... },
          error   : function ( retobj ) { ... },
          ...
          } );

is called? Can my controller directly control which is called? I know it'll be called if my controller does something stupid, but can I force it to be called like

$.ajax( { ...,
          url     : 'MyController/CallSuccess',
          success : function ( retobj ) { /* this will invetiably be called */},
          error   : function ( retobj ) { ... },
          ...
          } );

 public ActionResult CallSuccess ( void )
 {
    // ...
 }

1 Answers1

0

Your controller action method can control whether the success or error ajax function will be called via setting the Response.StatusCode in your action method.

If Response.StatusCode = (int)HttpStatusCode.OK then the success function will be called.

If Response.StatusCode = (int)HttpStatusCode.InternalServerError then the error function will be called.

Sample code to invoke success function:

    $.ajax({
      url: 'MyController/CallSuccess',
      success: function(result) { /* this will be called */
        alert('success');
      },
      error: function(jqXHR, textStatus, errorThrown) {
        alert('oops, something bad happened');
      }
    });

    [HttpGet]
    public ActionResult CallSuccess()
    {
        Response.StatusCode = (int)HttpStatusCode.OK;
        return Json(new { data = "success" }, JsonRequestBehavior.AllowGet);
    }

Sample code to invoke error function:

    $.ajax({
      url: 'MyController/CallFailure',
      success: function(result) { 
        alert('success');
      },
      error: function(jqXHR, textStatus, errorThrown) { /* this will be called */
        alert('oops, something bad happened');
      }
    });

    [HttpGet]
    public ActionResult CallFailure()
    {
        Response.StatusCode = (int)HttpStatusCode.InternalServerError;
        return Json(new { data = "error" }, JsonRequestBehavior.AllowGet);
    }
Clive Seebregts
  • 2,004
  • 14
  • 18