立即重定向到操作

本文关键字:操作 重定向 | 更新日期: 2023-09-27 18:12:25

问题


嗨,当找不到Department时,我正试图在控制器中重定向到另一个操作。我的问题是,它不会在我点击代码块后立即重定向。我不确定这是否是正确的方法,但对我来说,它似乎应该有效。我也不喜欢使用Response.Redirect(url);,因为这对我来说有点乱

代码


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

此外



是否还有一种向Index()操作发送错误的好方法?例如,我会/可以/应该用viewbag这样做吗?还是这真的只针对视图?

提前谢谢。

立即重定向到操作

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

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

至于保存错误状态,您可以使用TempData容器,它将在重定向后继续存在,但不会持续更长时间。(另请参阅ASP.NET MVC3中TempData的正确使用?(。例如:

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

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

您需要返回重定向结果:

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()一样(。

确保返回结果

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

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

看看这里。

参考

MSDN

向Index((发送错误

我假设您想在Index((中显示错误,请使用TempData并在Index((上渲染它。

您可以选中null并在Index((中显示它;