带有Ajax.Beginform的RedirectToAction,意外结果

joh*_* Gu 8 asp.net-mvc ajax.beginform razor asp.net-mvc-4

我有以下视图,其中包含一个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>
Run Code Online (Sandbox Code Playgroud)

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

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



        }
Run Code Online (Sandbox Code Playgroud)

将在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');
    }

}
Run Code Online (Sandbox Code Playgroud)

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

Zab*_*sky 16

操作成功时,返回要从操作方法重定向的URL:

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

并在createsuccess:

function createsuccess(data) {
    if (data.RedirectUrl)
        window.location.href = data.RedirectUrl;
}
Run Code Online (Sandbox Code Playgroud)

  • 这是 **one liner** `return JavaScript( "window.location = '" + Url.Action("Home","Details") + "'" )` 检查 [this](http://stackoverflow.com /questions/1538523/how-to-get-an-asp-net-mvc-ajax-response-to-redirect-to-new-page-instead-of-inser),希望对某人有所帮助。 (3认同)