usr4896260 usr4896260 - 6 months ago 62
Javascript Question

Razor MVC 5.2.3 how to call OnFailure with ajax post

I have a ajax form in which I would like to call two different javascript functions, one for success and one for failure. In both of these calls, I pass data back from the server to the javascript. Please note the following:

I have this in my view

@using (Ajax.BeginForm("MyAction", null,
new AjaxOptions
{
HttpMethod = "POST", // HttpPost
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "myDiv",
OnSuccess = "callSuccess(data.msg)",
OnFailure = "callFailure(data.msg)",
}, new { @class = "form-inline" }))
{
... // my content
}


My controller has the following logic when return the post.

public ActionResult MyAction(string myString)
{
...
// If error occurred
return Json(new { success = false, msg= "Fail" });
...
// If no errors
return Json(new { success = true, msg= "Success" });
}


No matter what is returned,
OnSuccess
is the only one that gets called. What is the proper way to call
OnFailure
?

Answer

With the help from Rion Williams post, I was able to call both functions. More importantly, I figured out how to access and display the desired message upon success/failure:

My controller

public ActionResult MyAction(string myString)
{
    ...
    // If error occurred
    return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Error occurred!");
    ...
    // If no errors
    return Json(new { success = true, msg= "Success" });
}

My view:

@using (Ajax.BeginForm("MyAction", null,
new AjaxOptions
{
    HttpMethod = "POST", // HttpPost
    InsertionMode = InsertionMode.Replace, 
    UpdateTargetId = "myDiv", 
    OnSuccess = "callSuccess(data.msg)",
    OnFailure = "callFailure(error)",    // error = "Error occurred!"
}, new { @class = "form-inline" }))
{
   ... // my content
}