asp.net-mvc-3 – 可以重定向到新页面的Ajax.BeginForm

我有一个@ 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");
        }
    }

解决方法

您可以使用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");
    }
}

接着:

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

最后:

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

相关文章

引言 本文从Linux小白的视角, 在CentOS 7.x服务器上搭建一个...
引言: 多线程编程/异步编程非常复杂,有很多概念和工具需要...
一. 宏观概念 ASP.NET Core Middleware是在应用程序处理管道...
背景 在.Net和C#中运行异步代码相当简单,因为我们有时候需要...
HTTP基本认证 在HTTP中,HTTP基本认证(Basic Authenticatio...
1.Linq 执行多列排序 OrderBy的意义是按照指定顺序排序,连续...