Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC controller.Execute with areas

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?

like image 979
Diego Avatar asked Apr 10 '13 19:04

Diego


1 Answers

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");
//...
like image 188
nemesv Avatar answered Sep 21 '22 19:09

nemesv