Practical ASP.NET

Nesting Layouts in ASP.NET MVC

If you've got a site that contains subsites and want to visually distinguish between those subsites (while still maintaining your site's visual integrity), consider nesting layouts within layouts.

It's worth remembering that the layout View you use in your site really is just a View: Pretty much anything you can do in a View, you can do in your layout View, including setting the Layout property. This can be useful if you have a site that's made up of several subsites because it lets you simplify the process of giving all of your subsites a distinct look-and-feel while maintaining an overall look-and-feel for the whole site.

To exploit this feature, first create a Layout for your whole site, leaving space in the View for your subsites to supply their HTML. Add to this view any site-wide stylesheets and script libraries that you use everywhere (the jQuery library would be a good choice, for example). This will probably be a pretty minimal View consisting, perhaps, only of the company logo, contact information and legal disclaimers. This View probably will just have a single RenderBody method and not use RenderSection.

Then create layout Views for each of your subsites, leaving space in those Views for the actual content that the Views called directly from Action methods will supply. In these subsite's layout Views, set their Layout property to your site-wide view:

@Code
  Layout = "~/Views/Shared/_Master.cshtml"
End Code

This is where you can put any stylesheets that tailor the subsite's appearance (or, really, any other resource used only in the subsite). This View is more likely to use RenderSection in order to provide more options for placing the variety of content required by your subsite's Views. Of course, if you've used RenderSection in your full-site layout, these are the Views where you'll define those sections.

There's another benefit in using this technique: When you want to change the appearance of a subsite you can do that in the subsite's layout View, knowing that you won't be doing harm to some other subsite's appearance.

About the Author

Peter Vogel is a system architect and principal in PH&V Information Services. PH&V provides full-stack consulting from UX design through object modeling to database design. Peter tweets about his VSM columns with the hashtag #vogelarticles. His blog posts on user experience design can be found at http://blog.learningtree.com/tag/ui/.

comments powered by Disqus

Featured

Subscribe on YouTube