madvora
madvora

Reputation: 1747

JQuery AJAX Success With Multiple MVC Controller Methods

Let's say I post a form to an MVC controller and action like this

function ajaxFunction() {        
    $.ajax({
        type: "POST",
        url: "ControllerName/FirstMethod",
        data: $('#form').serialize(),
        success: function () {
            //I'm wondering if this gets run after the FirstMethod or SecondMethod   
        }
    });
)

The controller action does something, then redirects to the next method like this

[HttpPost]
public ActionResult FirstMethod()
{
    //Some code run here

    //Send to the next method
    return RedirectToAction("SecondMethod");
}

public void SecondMethod()
{
    //Something else done here
}

So the whole process is to post to the FirstMethod, then run the SecondMethod. My question is - when does the Ajax success() method run? Is it after the FirstMethod or SecondMethod?

Upvotes: 2

Views: 141

Answers (1)

Brad C
Brad C

Reputation: 2982

RedirectToAction returns a HTTP status code of 302, which makes AJAX do a GET to the redirect URL (SecondMethod).

jQuery AJAX success only gets called when a 2XX HTTP code is returned. If SecondMethod returns something with a 2XX status code (such as a View), it will be then. Otherwise, it will never be called.

Upvotes: 2

Related Questions