Search code examples
asp.net-mvcrazorstack-overflow

Why do I get a StackOverflowException when using Html.RenderAction in Razor?


I am converting a WebForms application to Razor and everything works fine except when I try to use Html.RenderAction. Whenever I call this, I get a StackOverflowException. Does anyone have an idea on what might be causing this?

The template for my action looks like this:

@model dynamic   

should be rendering this

In my _Layout.cshtml file I render the action like this:

@{Html.RenderAction("MyPartialAction");}

My _ViewStart.cshtml file looks as follows:

@{
    this.Layout = "~/Views/Shared/_Layout.cshtml";
}

Solution

  • The problem is that your template for your action does not define a Layout to be used. Therefore, it automatically gets the one specified in the _ViewStart.cshtml file. This will in effect cause the _Layout.cshtml file to be nested within itself ad infinitum. Hence the StackOverflowException. The solution is simple. Set the Layout within your action template to null:

    @model dynamic
    @{
       Layout = null;
    }
    should be rendering this
    

    Now the template won't request to be embedded in a layout file and everything works fine.