RedirectToAction with Ajax.Beginform, unexpected results

I have the following view that contains 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> 

and the following action method, which will be called from 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); } } 

script to be run when Ajax.BeginForm returns success: -

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

I am currently facing a problem, since when reaching RedirectToAction the whole view will be displayed inside the current view !! so is there a way to prevent my application from updating the target if RedirecttoAction returns?

+7
asp.net-mvc razor asp.net-mvc-4 ajax.beginform
source share
2 answers

Return the URL that you want to redirect from the action method on a successful operation:

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

And in createsuccess :

 function createsuccess(data) { if (data.RedirectUrl) window.location.href = data.RedirectUrl; } 
+13
source share

in my case, the following method was processed

 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; } 
0
source share

All Articles