OdeToCode IC Logo

Stackoverflow Exceptions with Html.Action

Wednesday, February 9, 2011

If you ever have a stack overflow using Html.Action or Html.RenderAction in a Layout view, then check the return type of your child action.

public class Weather : Controller 
{
    public ActionResult Forecast()
    {
        // ...

        return View();
    }
}

The problem is if you call that action from a Layout view, like so:

@Html.Action(actionName: "Forecast", 
             controllerName: "Weather")

... then the child action is returning a ViewResult (which will pick up a Layout from the default _ViewStart, and the Layout renders the child action, which returns a ViewResult, which picks up a Layout, and so on).

There is a simple fix - make sure you return a PartialViewResult from the child action.

public class WeatherController : Controller
{
    public ActionResult Forecast()
    {
        // ...

        return PartialView();
    }
}