2016-03-08 67 views
0

單擊超鏈接時,我想在應用業務邏輯後導航到頁面。目前,mvc動作中的「返回重定向(Url)」不會導航到該頁面。MVC重定向不會導航到頁面

$("a").bind("click", function (e) { 
     e.preventDefault(); 
     gotoUrl($, this.href); 
    }); 

gotoUrl: function ($, href) { 
    $.ajax({ 
      type: "POST", 
      url: 'mycontroller/myaction', 
      data: { url: href }, 
      dataType: 'json', 
      cache: false 
      success: function (data) { }   
     }); 
} 

//mycontroller 
[HttpPost] 
public ActionResult myaction(string url) 
{ 
    //Some business logic here to update url 
    return Redirect(url); 
} 

回答

0

爲了改變當前窗口的位置,你需要檢測你的Ajax請求被重定向(事後手動重定向),東西是不可能的,因爲jQuery將跟隨重定向。在類似的情況下,我實施了以下更通用的解決方法,但您可以根據需要進行調整。

在global.asax中爲Application_EndRequest創建處理程序,攔截重定向響應並將響應代碼重寫爲表示錯誤的其他東西,我使用代碼422 - 不可處理的實體。

protected void Application_EndRequest() 
{ 
if (Context.Response.StatusCode == 302 && Context.Request.IsAjaxRequest()) 
{ 
    Context.Response.StatusCode = 422; 
} 
} 

在您的客戶端腳本中,您現在需要通過添加通用ajax錯誤處理程序來檢測這些422響應。

$(document) 
    .ajaxError(function (e, xhr, settings) { 
    if (xhr.status == 422) { 
    window.location = xhr.getResponseHeader('Location'); 
    } 
    })