Tuesday, 30 November 2010

@Html.RenderAction caused StackOverflowException


_Layout.cshtml file uses @Html.RenderAction(“Menu”, “Nav”) to render the menu.

And the NavController has the following code

By doing so, we can generate menu dynamically. But the above code throws an exception: StackOverflowException, the code is working perfectly using WebFormViewEngine, but is not working for RazorViewEngine.


The cause of the above exception is the newly introduced "_ViewStart.cshtml" file. The code inside "_ViewStart.cshtml" will run before rendering any view, and currently the content of _ViewStart.cshtml is very simple,

It just set the current layout. As NavController's Menu() action simply returns View(), it causes "_ViewStart.cshtml" to kick in, which in turn renders _Layout.cshtml again, which call Html.RenderAction("Menu", "Nav") again, thus causes infinite loop and eventually throws StackOverflowException.


The fix to the above error is very simple, just change the NavController's Menu() action as follows will fix the issue, because PartialView() will not execute "_ViewStart.cshtml" file, hence avoids the infinite loop.


Banksy said...

Thanks for posting this! Just saved me time chasing my tail.

Anonymous said...

same here! Thanks much.

Anonymous said...