2016-03-15 45 views
3

我有一種情況,我需要返回一個JSONResult或重定向。 這可能嗎?如何根據輸入以相同方法返回JsonResult或ActionResult?

例子:

public ActionResult Example(string code) 
{ 
    if(string.IsNullorEmpty(code)) 
    return RedirectToAction("Index", "Home"); 
    else 
    return Json(new { success = true, message= "Next step"}); 
} 
+2

是的,有可能同時返回,因爲他們是'ActionResults'。但是,如果您在Ajax調用中返回'RedirectToAction',它將不會重定向。這是你的問題嗎? –

回答

3

是的,這是可能的。事實上,你發佈的代碼就是你如何做的!

Controller.RedirectToAction返回a RedirectToRouteResult,Controller.Json返回JsonResult。他們都從ActionResult繼承,所以返回他們作爲ActionResult將工作得很好。


如果你正在使用AJAX工作:

即使你沒有說你打電話背景是什麼,由insightful comment by Thiago Ferreira提到,重定向不使用AJAX工作。 您需要返回錯誤消息,然後在客戶端處理它。

例如你的操作方法:

public ActionResult Example(string code) 
{ 
    if(string.IsNullorEmpty(code)) 
    { 
     UrlHelper urlHelper = new UrlHelper(HttpContext.Request.RequestContext); 
     string actionUrl = urlHelper.Action("Index", "Home"); 
     return Json(new { success = false, message = "Code not provided", redirectTo = actionUrl}); 
    } 
    else 
    { 
     return Json(new { success = true, message= "Next step"}); 
    } 
} 

處理它在客戶端:

if(response.success) { 
    // yay 
} else if(response.redirectTo) { 
    window.location.href = response.redirectTo; 
} 
+0

此方法可能是首選,但是您可以*返回JsonResult或RedirectToAction。儘管您必須讓Ajax調用的成功/失敗/完成功能能夠檢查響應是返回的視圖還是json對象。否則,回調函數將不知道是否渲染內容,將哪個DOM元素插入其中,還是隻能根據Json執行一些邏輯。 – Erik

+0

但是在哪種情況下我們可以在單一方法中同時使用?事實上呢? –

相關問題