Tuesday 30 November 2010

@Html.RenderAction caused StackOverflowException

Background

_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.

Cause

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.

Fix

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.

Wednesday 10 November 2010

ASP.NET MVC3 Release Candidate

Today, ASP.NET team just announced the ASP.NET MVC 3 Release Candidate, you can download it from Microsoft download center.

It includes a bunch of new features and makes ASP.NET MVC development much easier. The main change compare to Beta version is the Razor Intellisense within Visual Studio. The RC support colorization and intellisense for the new Razor view engine. Intellisense works with HTML, C#, VB, Javascript and CSS.