MVC controller.Execute with areas
Asked Answered
C

1

5

I've a site in MVC4 using areas. In some area (lets call it Area), I have a controller (Controller) with this actions:

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

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

This works great if I make a simple redirect to Area/Controller/OtherAction like this:

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

But I need (check here why) to make a redirect like this:

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));

And in that case it doesn't work. After the last line, the OtherAction method is executed and then in the last line of this code it throws this exception:

The view 'Index' or its master was not found or no view engine supports the searched locations. The following locations were searched:

~/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

Why is this happening and how can I fix it?

Cocci answered 10/4, 2013 at 19:48 Comment(0)
U
13

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");
//...
Ultrasonics answered 10/4, 2013 at 20:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.