asp.net-mvc – 使用Ajax.Beginform的RedirectToAction,意外结果

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 使用Ajax.Beginform的RedirectToAction,意外结果前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下视图,其中包含一个Ajax.BeginForm: –
  1. @using (Ajax.BeginForm("ChangeDevicesSwitch","Switch",new AjaxOptions
  2.  
  3. {
  4. InsertionMode = InsertionMode.InsertBefore,UpdateTargetId = "result",LoadingElementId = "progress2",HttpMethod= "POST",OnSuccess = "createsuccess",OnFailure = "createfail"
  5.  
  6.  
  7.  
  8.  
  9. }))
  10. //code goes here
  11. <p><img src="~/Content/Ajax-loader-bar.gif" class="loadingimage" id="progress2" /></p>
  12. <div id ="result"></div>

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

  1. public ActionResult ChangeDevicesSwitch(SwitchJoin s)
  2.  
  3. {//code goes here
  4. try
  5. {
  6. var count = repository.changeDeviceSwitch(s.Switch.SwitchID,(Int32)s.GeneralSwitchTo,User.Identity.Name.Substring(User.Identity.Name.IndexOf("\\") + 1));
  7. repository.Save();
  8. return RedirectToAction("Details",new { id = s.GeneralSwitchTo });
  9.  
  10. }
  11. catch (Exception e)
  12.  
  13. {
  14. return Json(new { IsSuccess = "custome",description = "Error occurred. Please check...." },JsonRequestBehavior.AllowGet);
  15. }
  16.  
  17.  
  18.  
  19. }

将在Ajax.BeginForm返回成功时运行的脚本是: –

  1. function createsuccess(data) {
  2. if (data.IsSuccess == "Unauthorized") {
  3.  
  4. jAlert(data.description,'Unauthorized Access');
  5. }
  6. else if (data.IsSuccess == "False") {
  7.  
  8. jAlert('Error Occurred. ' + data.description,'Error');
  9. }
  10. else if (data.IsSuccess == "custome") {
  11.  
  12. alert(data.description);
  13.  
  14. }
  15. else {
  16. jAlert('Record added Successfully ','Creation Confirmation');
  17. }
  18.  
  19. }

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

解决方法

操作成功时,返回要从操作方法重定向的URL:
  1. public ActionResult ChangeDevicesSwitch(SwitchJoin s)
  2. {
  3. try
  4. {
  5. ...
  6. return Json(new { RedirectUrl = Url.Action("Details",new { id = s.GeneralSwitchTo }) });
  7. }
  8. ...
  9. }

并在创建成功:

  1. function createsuccess(data) {
  2. if (data.RedirectUrl)
  3. window.location.href = data.RedirectUrl;
  4. }

猜你在找的asp.Net相关文章