How can I RedirectToAction within $.ajax callback?
Asked Answered
S

4

17

I use $.ajax() to poll an action method every 5 seconds as follows:

$.ajax({
    type: 'GET', url: '/MyController/IsReady/1',
    dataType: 'json', success: function (xhr_data) {
        if (xhr_data.active == 'pending') {
            setTimeout(function () { ajaxRequest(); }, 5000);                  
        }
    }
});

and the ActionResult action:

public ActionResult IsReady(int id)
{
    if(true)
    {
        return RedirectToAction("AnotherAction");
    }
    return Json("pending");
}

I had to change the action return type to ActionResult in order to use RedirectToAction (originally it was JsonResult and I was returning Json(new { active = 'active' };), but it looks to have trouble redirecting and rendering the new View from within the $.ajax() success callback. I need to redirect to "AnotherAction" from within this polling ajax postback. Firebug's response is the View from "AnotherAction", but it's not rendering.

Soupandfish answered 20/8, 2010 at 21:17 Comment(0)
C
20

You need to consume the result of your ajax request and use that to run javascript to manually update window.location yourself. For example, something like:

// Your ajax callback:
function(result) {
    if (result.redirectUrl != null) {
        window.location = result.redirectUrl;
    }
}

Where "result" is the argument passed to you by jQuery's ajax method after completion of the ajax request. (And to generate the URL itself, use UrlHelper.GenerateUrl, which is an MVC helper that creates URLs based off of actions/controllers/etc.)

Circumsolar answered 20/8, 2010 at 21:29 Comment(1)
found something similar on another post after exhaustive searching. only difference was that it used window.location.replace instead. thanks!Soupandfish
E
4

I know this is a super old article but after scouring the web this was still the top answer on Google, and I ended up using a different solution. If you want to use a pure RedirectToAction this works as well. The RedirectToAction response contains the complete markup for the view.

C#:

return RedirectToAction("Action", "Controller", new { myRouteValue = foo});

JS:

 $.ajax({
    type: "POST",
    url: "./PostController/PostAction",
    data: data,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    complete: function (result) {
        if (result.responseText) {
            $('body').html(result.responseText);
        }
    }
});
Erepsin answered 10/3, 2016 at 14:26 Comment(0)
Z
2

C# worked well

I just changed the JS because responseText was not working for me:

 $.ajax({
        type: "POST",
        url: posturl,
        contentType: false,
        processData: false,
        async: false,
        data: requestjson,
        success: function(result) {
            if (result) {
                $('body').html(result);
            }
        },

        error: function (xhr, status, p3, p4){
            var err = "Error " + " " + status + " " + p3 + " " + p4;
            if (xhr.responseText && xhr.responseText[0] == "{")
                err = JSON.parse(xhr.responseText).Message;
            console.log(err);
        }
    });   
Zamarripa answered 20/12, 2016 at 0:33 Comment(1)
If you add the parametter "dataType: 'json'" to your request, you will get the required responseText variable in the result.Claribel
Z
0

You could use the Html.RenderAction helper in a View:

public ActionResult IsReady(int id)
{
    if(true)
    {
        ViewBag.Action = "AnotherAction";
        return PartialView("_AjaxRedirect");
    }
    return Json("pending");
}

And in the "_AjaxRedirect" partial view:

@{
    string action = ViewBag.ActionName;
    Html.RenderAction(action);
}

Reference: https://mcmap.net/q/174366/-how-to-simulate-server-transfer-in-asp-net-mvc

Zooplasty answered 7/3, 2018 at 11:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.