Thursday, February 3, 2011

ASP.NET MVC3 Html.RenderAction infinite loop / stackoverflow

I have started learning some MVC and recently switched over to the MVC3 Razor view engine. I was trying to generate a menu from a controller action and use it on my Layout page so that it was viewable to all pages. So I created a NavController and a Menu() action method with corresponding view. For simplicity, the action just passed an IEnumerable model to the view, which it used to form an unordered list of action links.

I then used Html.RenderAction in the Layout page to render the menu. To my surprise, I got a stack overflow. Upon debugging i realized that it was looping over the action method again and again.

It turns out...and I'm assuming this is Razor specific but have no idea... that if you return a ViewResult from your action method, it will reference the Layout page and call the RenderAction method again. Which returns another ViewResult and references the Layout page again. And again. And again. Until it causes a crash.

The solution was to return a PartialViewResult from the Menu() action, instead of ViewResult. This eliminated the infinite loop and correctly rendered my menu.