立即RedirectToAction

时间:2014-07-11 12:28:24

标签: c# .net

问题


嗨,我无法在找不到Department的情况下尝试重定向到我的控制器中的其他操作。我的问题是它在我点击代码块后没有立即重定向。我不确定这是否是正确的方法,但对我而言似乎应该有效。我也不想使用Response.Redirect(url);,因为这对我来说似乎有些混乱。

代码


if(errors.Count > 0)
{
    RedirectToAction("Index", "Department"); //Redirect to the index page, because the department could not be found
}

另外



是否还有一种向Index()动作发送错误的好方法?是/可能/我应该使用一个视图包,或者仅仅是视图?

提前致谢。

5 个答案:

答案 0 :(得分:3)

您需要返回重定向结果:

if(errors.Count > 0)
{
    return RedirectToAction("Index", "Department"); //Redirect to the index page, because the department could not be found
}

这样,方法的执行结束,ActionResult返回给客户端,在这种情况下是RedirectToAction结果。

基本上,在MVC中,其中一个目标是将代码与HTTP上下文分离。因此,不是直接对Response对象进行操作(与Response.Redirect()一样),而只是从操作方法返回不同的响应类型。

答案 1 :(得分:3)

RedirectToAction(...)会从控制器方法返回RedirectToActionResult,而您需要return

if(errors.Count > 0)
{
    //Redirect to the index page, because the department could not be found
    return RedirectToAction("Index", "Department"); 
}

就保存错误状态而言,您可以使用TempData容器,该容器将在重定向后继续存在但不会持续更长时间。 (另见Proper use of TempData in ASP.NET MVC3?)。例如:

TempData["ErrorMessage"] = "The department was not found";

然后,您可以检查Index()方法中的数据并采取相应措施。

答案 2 :(得分:0)

确保返回结果

return RedirectToAction("Index", "Department"); //Redirect to the index page, because the department could not be found

答案 3 :(得分:0)

你应该这样做 return RedirectToAction("Action","Controller");

看看这里。

Reference

MSDN

答案 4 :(得分:0)

向Index()

发送错误

我假设您要在Index()中显示错误,使用TempData并在Index()上呈现它。

您可以检查null并在Index();

中显示它