【问题标题】:RedirectToAction with Ajax.Beginform , unexpected resultsRedirectToAction 与 Ajax.Beginform ,意外结果
【发布时间】:2014-05-21 14:55:09
【问题描述】:

我有以下视图,其中包含一个 Ajax.BeginForm:-

@using (Ajax.BeginForm("ChangeDevicesSwitch", "Switch", new AjaxOptions

{
    InsertionMode = InsertionMode.InsertBefore,
    UpdateTargetId = "result",
    LoadingElementId = "progress2",
    HttpMethod= "POST"
    ,
    OnSuccess = "createsuccess",
    OnFailure = "createfail"




}))
//code goes here
<p><img src="~/Content/Ajax-loader-bar.gif" class="loadingimage" id="progress2" /></p>
<div id ="result"></div>

以及将从 Ajax.Bginform 调用的以下操作方法:-

public ActionResult ChangeDevicesSwitch(SwitchJoin s)

        {//code goes here
            try
            {
                var count = repository.changeDeviceSwitch(s.Switch.SwitchID, (Int32)s.GeneralSwitchTo, User.Identity.Name.Substring(User.Identity.Name.IndexOf("\\") + 1));
                repository.Save();
                return RedirectToAction("Details", new { id = s.GeneralSwitchTo });

            }
            catch (Exception e)

            {
                return Json(new { IsSuccess = "custome", description = "Error occurred. Please check...." }, JsonRequestBehavior.AllowGet);
            }



        }

Ajax.BeginForm 返回成功时运行的脚本是:-

function createsuccess(data) {
    if (data.IsSuccess == "Unauthorized") {

        jAlert(data.description, 'Unauthorized Access');
    }
    else if (data.IsSuccess == "False") {

        jAlert('Error Occurred. ' + data.description, 'Error');
    }
    else if (data.IsSuccess == "custome") {

        alert(data.description);

    }
    else  {
        jAlert('Record added Successfully ', 'Creation Confirmation');
    }

}

目前我面临的一个问题是,当 RedirectToAction 到达时,整个视图将显示在当前视图中!那么有没有办法强制我的应用程序在返回 RedirecttoAction 时不更新目标?

【问题讨论】:

  • 您不能通过 ajax 进行重定向。相反,您可以将重定向 url 发送回客户端,并在 createsuccess 函数上将 window.location 设置为提供的 url。
  • 您能否通过示例代码对此提供更多建议

标签: asp.net-mvc asp.net-mvc-4 razor ajax.beginform


【解决方案1】:

当操作成功时,从action方法返回你要重定向到的url:

public ActionResult ChangeDevicesSwitch(SwitchJoin s)
{
    try
    {
        ...
        return Json(new { RedirectUrl = Url.Action("Details", new { id = s.GeneralSwitchTo }) });
    }
    ...
}

而在createsuccess

function createsuccess(data) {
    if (data.RedirectUrl)
        window.location.href = data.RedirectUrl;
}

【讨论】:

  • 这里是一个班轮 return JavaScript( "window.location = '" + Url.Action("Home","Details") + "'" )检查this,希望对某人有所帮助。
【解决方案2】:

在我的情况下,以下方法有效

function OnSuccess(data) {
    var json;
        if (data.responseText instanceof Object)
            json = data.responseText;
        else
            json = $.parseJSON(data.responseText);

        if (json.RedirectUrl)
            window.location.href = json.RedirectUrl;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-21
    • 2023-04-01
    • 2015-11-03
    • 2021-09-18
    • 1970-01-01
    • 1970-01-01
    • 2015-12-24
    • 1970-01-01
    相关资源
    最近更新 更多