Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
811 views
in Technique[技术] by (71.8m points)

asp.net mvc - How can I RedirectToAction within $.ajax callback?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...