2012-09-07 16 views
3

我想對我的行動的呼籲,並有行動要麼返回直接渲染到視圖或有動作所產生的局部視圖重定向到另一頁在服務器上。調用從jQuery的MVC動作和處理重定向或返回的局部視圖

然而,因爲我通過jQuery這樣做似乎重定向的頁面加載到我的目標div元素,而不是重定向乾淨,有效地重新加載頁面/網站。

jQuery的電話:

$.ajax({ 
    type: "GET", 
    url: "Myurl", 
    dataType: "html", 
    success: function (data) { 
     // replace the context of the section with the returned partial view 
     $('#upload_section').html(data); 
    } 
}); 

MVC動作例如

public ActionResult MyAction() 
{ 
    bool doRedirect = // some code to determine this condition 
    if (doRedirect) 
    { 
     return RedirectToAction("MyAction", "Home"); 
    } 
    else 
    { 
     // return the partial view to be shown 
     return PartialView("_UploadSessionRow"); 
    } 
} 

我這樣做都是錯的?有沒有更好的做法呢?有必要做,所以I''m尋找如何去這一個共同的方法將發生在其他動作和jQuery請求。

更新: 感謝安德魯斯答案我得到了什麼後,通過改變我的ajax,根據他的建議進行了一些修改。最終阿賈克斯是:

function loadOrRedirect(options) { 

    var jData = null; 

    try {  
     if (options.data) { 
      jData = $.parseJSON(options.data); 

      if (jData.RedirectUrl) { 
       window.location = jData.RedirectUrl; 
      } 
     } 
    } catch (e) { 
     // not json 
    } 

    if (!jData && options.callback) { 
     options.callback(options.data); 
    } 
}; 

$.ajax({ 
    type: "GET", 
    url: "Myurl", 
    dataType: "html", 
    success: function (data) { 
     loadOrRedirect(
         { 
          data: data, 
          callback: function (html) { 
            replaceRow.replaceWith(html); 
            alternateRowHighlighting(); 
         } 
     }); 
} 

});

+0

可能重複[RedirectToRoute( 「默認」)和重定向(RETURNURL)正在返回 '200',而不是「302 「(http://stackoverflow.com/questions/2355151/redirecttoroutedefault-and-redirectreturnurl-are-returning-200-instead-o) - 關於這個問題的OP基本上是做你(AJAX負載或重定向)什麼 –

回答

18

您無法從AJAX請求重定向。你將不得不從JavaScript做重定向。我建議是這樣的:

public ActionResult MyAction() 
{ 
    bool doRedirect = // some code to determine this condition 
    if (doRedirect) 
    { 
     return Json(new 
     { 
      RedirectUrl = Url.Action("MyAction", "Home") 
     }); 
    } 
    else 
    { 
     // return the partial view to be shown 
     return PartialView("_UploadSessionRow"); 
    } 
} 

然後在JavaScript端:

$.ajax({ 
    type: "GET", 
    url: "Myurl", 
    dataType: "html", 
    success: function (data) { 
     if (data.RedirectUrl) { 
      window.location = data.RedirectUrl; 
     } else { 
      // replace the context of the section with the returned partial view 
      $('#upload_section').html(data); 
     } 
    } 
}); 
+0

謝謝安德魯。我會放棄它。 – dreza

+0

是的,工作一種享受一些小的MODS的,我在我的答案更新 – dreza

0

你可能使用success回調的第二個或第三個參數來決定該怎麼做。無論如何,因爲您使用的是Ajax,您將無法進行正常的重定向。您可能必須通過javascript執行輔助重定向,或將整個頁面替換爲從RedirectToAction返回的內容

+0

乾杯約翰。我設法通過返回一個Json對象來做到這一點,並在javascript中進行重定向。 – dreza