5

我在 MVC4 中有一个使用区域的站点。在某些区域(我们称之为区域),我有一个具有以下操作的控制器(控制器):

public ActionResult Index()
{
    return View();
}

public ActionResult OtherAction()
{
    return View("Index");
}

如果我像这样简单地重定向到 Area/Controller/OtherAction,这将非常有用:

return RedirectToAction("OtherAction", "Controller", new { area = "Area" });

但我需要(在这里查看原因)进行这样的重定向:

RouteData routeData = new RouteData();
routeData.Values.Add("area", "Area");
routeData.Values.Add("controller", "Controller");
routeData.Values.Add("action", "OtherAction");
ControllerController controller = new ControllerController();
controller.Execute(new RequestContext(new HttpContextWrapper(HttpContext.ApplicationInstance.Context), routeData));

在这种情况下,它不起作用。在最后一行之后,OtherAction 方法被执行,然后在这段代码的最后一行,它抛出了这个异常:

未找到视图“索引”或其主视图,或者没有视图引擎支持搜索的位置。搜索了以下位置:

~/Views/Controller/Index.aspx

~/Views/Controller/Index.ascx

~/Views/Shared/Index.aspx

~/Views/Shared/Index.ascx

~/Views/Controller/Index.cshtml

~/Views/Controller/Index.vbhtml

~/Views/Shared/Index.cshtml

~/Views/Shared/Index.vbhtml

为什么会发生这种情况,我该如何解决?

4

1 回答 1

12

You get the exception because ASP.NET MVC tries to look up your view in the "root" context and not inside the area view directory because you are not setting up the area correctly in the routeData.

The area key needs to be set in the DataTokens collections and not in the Values

RouteData routeData = new RouteData();
routeData.DataTokens.Add("area", "Area");
routeData.Values.Add("controller", "Controller");
routeData.Values.Add("action", "OtherAction");
//...
于 2013-04-10T20:06:27.190 回答