可以重定向到新页面的Ajax.BeginForm

Cal*_*ass 23 asp.net-mvc-3

我的@Ajax.BeginForm模型有一个布尔值(@Html.CheckBoxFor).如果选中此选项,我希望我的HttpPost操作重定向到新页面.否则我希望它继续作为@Ajax.BeginForm并更新页面的一部分.

这是我的HttpPost动作(注意:Checkout是我模型中的布尔值)

控制器:

    [HttpPost]
    public ActionResult UpdateModel(BasketModel model)
    {
        if (model.Checkout)
        {
            // I want it to redirect to a new page
            return RedirectToAction("Checkout");
        }
        else
        {
            return PartialView("_Updated");
        }
    }
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 43

您可以使用JSON并在客户端上执行重定向:

[HttpPost]
public ActionResult UpdateModel(BasketModel model)
{
    if (model.Checkout)
    {
        // return to the client the url to redirect to
        return Json(new { url = Url.Action("Checkout") });
    }
    else
    {
        return PartialView("_Updated");
    }
}
Run Code Online (Sandbox Code Playgroud)

然后:

@using (Ajax.BeginForm("UpdateModel", "MyController", new AjaxOptions { OnSuccess = "onSuccess", UpdateTargetId = "foo" }))
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

最后:

var onSuccess = function(result) {
    if (result.url) {
        // if the server returned a JSON object containing an url 
        // property we redirect the browser to that url
        window.location.href = result.url;
    }
}
Run Code Online (Sandbox Code Playgroud)