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

时间:2014-05-21 14:55:10

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

我有以下视图,其中包含一个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调用的以下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);
            }



        }

当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,是否有办法强制我的应用程序不更新目标?

2 个答案:

答案 0 :(得分:16)

操作成功时,从操作方法返回要重定向的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;
}

答案 1 :(得分:0)

在我的情况下,以下方法已经完成

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