Gal Segal's Blog

Thoughts of a programmer with a soul

Mar 10

MVC Nested Layout

Tags: ,


MVC3 introduced Razor’s Layout as the new heir of the master page. It is a little different, has section rendering instead of content place holders, but it is pretty similar and intuitive to work with.

On the other day I had to create a layout within a layout. The reason for it was we have a basic, cross-website design, where in each page we have content in tabs, and each method on the controller is related to a tab. To support navigation between tabs by Ajax and by direct access for a url, each page should  be a layout it self, and each tab – a view. This view will be called from the controller.

I tried several ways to achieve it, but the best one I found was this:

  1. Create a MVC Layout Page has the master layout (“master layout”). Use “RenderBody()” where needed.
  2. Create a MVC View Page With Layout for the page,  and set its “Layout” property to the “master layout” (“page layout”). Use “RenderBody()” where needed.
  3. Create MVC View Page and set its “Layout” property to the “page layout”.
  4. Now you can call a method that will return the page.

One word about sections: It is a nice way of timing you html rendering:

We have a lot of JavaScript files on the the site, and we need to keep them in order. So, on the master layout we load all the infrastructure, dependencies etc. After we call “RenderSection(“PageScripts”, false)” to load the page scripts. Inside section “PageScripts” in the page layout we load additional scripts, and at the end we call “RenderSection(“TabScripts”, false)” to execute the specific tab scripts.

This mechanism ensures the all the dependencies were loaded in a correct order and the tab script can be executed.

Happy Coding :)

Back to top