如何在$ .ajax回调中使用RedirectToAction?
问题描述:
我使用$阿贾克斯()以查询操作方法每隔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' };
),但它在重定向和在$ .ajax()成功回调中呈现新视图时遇到问题。我需要在这个轮询ajax回发中重定向到“AnotherAction”。 Firebug的回应是来自“AnotherAction”的视图,但它不是渲染。
答
您需要使用您的ajax请求的结果并使用它来运行javascript以自己手动更新window.location。例如,像:
// Your ajax callback:
function(result) {
if (result.redirectUrl != null) {
window.location = result.redirectUrl;
}
}
其中“结果”是Ajax请求完成后由jQuery的AJAX方法传递给你的论点。 (并生成URL本身,使用UrlHelper.GenerateUrl
,这是一个MVC助手,创建基于动作/控制器/等URL)
答
我知道这是一个超级老的文章,但淘宝网后,这仍然是在谷歌最佳答案,我最终使用不同的解决方案。如果你想使用纯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);
}
发现了另一篇文章中类似的东西经过详尽的搜索。唯一不同的是它使用了window.location.replace。谢谢! – 2010-08-20 22:24:51