2012-02-01 86 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

相关问题