Ajax.BeginForm可以重定向到一个新页面 [英] Ajax.BeginForm that can redirect to a new page

查看:553
本文介绍了Ajax.BeginForm可以重定向到一个新页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

下面是我的HttpPost动作(注:结帐是在我的模型布尔值)

控制器:

  [HttpPost]
    公众的ActionResult的UpdateModel(BasketModel模型)
    {
        如果(model.Checkout)
        {
            //我希望它重定向到一个新的一页
            返回RedirectToAction(结帐);
        }
        其他
        {
            返回PartialView(_更新);
        }
    }


解决方案

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

  [HttpPost]
公众的ActionResult的UpdateModel(BasketModel模型)
{
    如果(model.Checkout)
    {
        //返回到客户端的URL重定向到
        返回JSON(新{URL = Url.Action(结帐)});
    }
    其他
    {
        返回PartialView(_更新);
    }
}

和则:

  @using(Ajax.BeginForm(的UpdateModel,myController的新AjaxOptions {=的onSuccess的onSuccess,UpdateTargetId =富}))
{
    ...
}

最后:

  VAR的onSuccess =功能(结果){
    如果(result.url){
        //如果服务器返回一个包含一个URL的JSON对象
        //财产,我们将浏览器重定向到URL
        window.location.href = result.url;
    }
}

I have an @Ajax.BeginForm for my model which has a boolean value (@Html.CheckBoxFor). If this is checked, I want my HttpPost action to redirect to a new page. Otherwise I want it to just continue being an @Ajax.BeginForm and update part of the page.

Here is my HttpPost action (Note: Checkout is the boolean value in my model)

Controller:

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

解决方案

You could use JSON and perform the redirect on the client:

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

and then:

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

and finally:

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

这篇关于Ajax.BeginForm可以重定向到一个新页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆