是否可以在mvc中使用带有RedirectToAction的$ .post

时间:2012-07-30 15:51:46

标签: asp.net asp.net-mvc

我是asp.net的新手,我使用$ .post(Jquery语法)将所有数据发布到服务器。

执行控制器的动作@结束我在完成动作方法执行后调用RedirectToAction到不同的动作方法。

执行到达$ .Post()的完成回调事件,其中我将html中的请求结果加载到页面的根元素。 $(HTML)的.html(结果)。

如何将$ .post与RedirectToAction一起使用

1 个答案:

答案 0 :(得分:2)

更换整个页面时使用AJAX有什么意义? AJAX的重点是只刷新DOM的某个部分。如果您要刷新整个页面,那么只需使用标准链接,无需使用AJAX。但是如果我们假设你的控制器动作处理了两种情况:一种是返回部分视图,另一种是重定向,你可以将目标URL作为JSON传递:

[HttpPost]
public ActionResult SomeAction()
{
    if (Something)
    {
        return PartialView();
    }

    return Json(new { redirectTo = Url.Action("Foo", "Bar") });
}

然后在客户端上:

$.post('@Url.Action("SomeAction")', function(result) {
    if (result.redirectTo) {
        // the controller action passed us the url to redirect to
        window.location.href = result.redirectTo;
    } else {
        // the controller action passed us a partial result => 
        // let's update some portion of the DOM
        $('#someId').html(result);
    }
});
相关问题