Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle Ajax.BeginForm() OnError OnFailure callback?

I have the following ajax post in my view:

@using (Ajax.BeginForm("UpdateEmail", new AjaxOptions
{
    HttpMethod = "POST",
    OnFailure = "showMessage(xhr.responseJSON.TypeMessage, xhr.responseJSON.Message)",
    OnSuccess = "showMessage(data.TypeMessage, data.Message); location.reload();",
    OnBegin = "$('#btnRefresh').attr('disabled', true)",
    OnComplete = "$('#btnRefresh').attr('disabled', false)",
 }))

And the controller:

public ActionResult UpdateEmail(EditEmailDTO model)
{      
        if (isValidCode)
        {
            //Code here to return a feedback json to be handle in OnSuccess callback - Working OK
            return new EmptyResult();
        }
        else 
        {
            //Here is the problem in production
            Response.StatusCode = 422; 
            feedback = new { Success = false, Message = MessageFeedback.InvalidCode, TypeMessage= TypeMessageFeedback.Error.ToString().ToLower() };
        }    
        catch (InvalidEmailException exception){ //Code Here    } 
        return Json(feedback, JsonRequestBehavior.AllowGet);
   }
}

When im debuggin locally it works perfectly, the OnFailure is fired and i get the feedback on screen. But when i deploy it i just see on the Chrome Dev Tools Console that the server returned a 422 error and this message: Uncaught TypeError: Cannot read property 'TypeMessage' of undefined.

The script generated in the Ajax.BeginForm() :

(function(xhr,status,error
 /**/) {
    showMessage(xhr.responseJSON.TypeMessage,        xhr.responseJSON.Message)
 })

Is there a difference in production and debuggin locally whith the Response.StatusCode errors?

like image 590
gog Avatar asked Oct 23 '25 18:10

gog


1 Answers

Well, I figure out the solution.

The problem is that IIS overrides the response in cases of errors (4xx and 5xx) response codes (even if is set manually on the Action method). Then the xhr object returned to the callback is the new object sent by the IIS and not my Json. The solution is to add this line on the Action:

Response.TrySkipIisCustomErrors = true;
like image 71
gog Avatar answered Oct 26 '25 08:10

gog



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!