2012-02-01 90 views
2

我有一個場景,我想重定向用戶,而他正在訪問一個頁面(GET,而不是POST),我想知道如何在ASP.Net MVC中執行此操作。你如何RedirectToAction()在一個GET,而不是在一個POST

這是場景。我有一個多步驟處理嚮導的控制器。雖然他已經完成了該步驟,但即使不太可能,用戶仍然可能嘗試訪問第1步。在這種情況下,我想重定向他第2步。

喜歡的東西:

public ViewResult Step1(int? id) 
{ 
    //Do some stuff and some checking here... 
    if (step1done) 
    { 
     return RedirectToAction("RegisterStep2"); 
    } 
} 

然而,這提供了以下錯誤,因爲RedirectToAction意味着在ActionResult的方法中使用:

無法隱式轉換類型「System.Web.Mvc.RedirectToRouteResult」到「System.Web.Mvc.ViewResult」

誰能告訴我如何解決這一問題,並有我的ViewResult方法(GET操作)進行重定向?是否應該像使用普通的舊ASP.Net一樣簡單地使用Response.Redirect(),或者是否有「更多ASP.Net MVC」的方式來執行此操作?

+0

只需將返回類型更改爲ActionResult,因爲您並不總是返回視圖。 – dotjoe 2012-02-01 17:30:35

+0

你必須在if子句後面有return語句。 – 2012-02-01 17:30:58

+0

@TomasJansson是的,謝謝。這只是一個過於簡單的代碼,只是爲了說明我在做什麼。 – 2012-02-02 22:14:04

回答

8

更改您的返回類型爲ActionResultViewResultRedirectToRouteResult的基類。

public ActionResult Step1(int? id) 
{ 
    //Do some stuff and some checking here... 
    if (step1done) 
    { 
     return RedirectToAction("RegisterStep2"); 
    } 

    // ... 

    return View(); 
} 
+0

我不知道GET操作可能會返回一個ActionResult。我認爲這僅適用於POST操作。我會嘗試的。 – 2012-02-02 22:12:47

6

變化ViewResultActionResult

public ActionResult Step1(int? id) 
{ 
    //Do some stuff and some checking here... 
    if (step1done) 
    { 
     return RedirectToAction("RegisterStep2"); 
    } 
} 

ViewResultActionResultabstract類派生。

+1

+1,因爲你也給出了正確的答案。 ;-) – 2012-02-03 02:44:10

相關問題