如何在$ .ajax回调中RedirectToAction?

我使用$ .ajax()每5秒轮询一次动作方法,如下所示:

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

和ActionResult动作:

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

我必须将动作返回类型更改为ActionResult才能使用RedirectToAction(最初它是JsonResult而我正在返回Json(new { active = 'active' }; ),但它看起来很难重定向并呈现新的View在$ .ajax()成功回调中。我需要从这个轮询ajax回发中重定向到“AnotherAction”.Firebug的响应是来自“AnotherAction”的视图,但它不是渲染。

您需要使用ajax请求的结果并使用它来运行javascript以手动更新window.location。 例如,类似于:

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

其中“result”是在完成ajax请求后由jQuery的ajax方法传递给您的参数。 (并且要生成URL本身,请使用UrlHelper.GenerateUrl ,它是一个基于actions / controllers /等创建URL的MVC帮助程序。)

我知道这是一篇超级老的文章,但在网上搜索后,这仍然是谷歌的最佳答案,我最终使用了不同的解决方案。 如果你想使用纯RedirectToAction,这也适用。 RedirectToAction响应包含视图的完整标记。

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); } } }); 

C#运作良好

我刚刚更改了JS,因为responseText对我不起作用:

  $.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); } }); 

您可以在视图中使用Html.RenderAction帮助程序:

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

并在“_AjaxRedirect”局部视图中:

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

参考: https : //stackoverflow.com/a/49137153/150342