Inherited layout in ASP.NET MVC

I have a default _Layout.cshtml layout for most pages. However, for some page groups, I would like to have a slightly modified default layout. I know that I can just copy this file by changing it a little, but that would mean duplicating the code and supporting two layouts with 99% of the same code.

I would like to inherit the layout from the default:

LayoutInherited.cshtml:

Layout = "~/Views/Shared/_Layout.cshtml"; ViewBag.BodyContentClassSpecial = ""; @section header{ <style> #body-content { width: 90%; margin: 0 auto; } </style> 

}

Can I do something like this?

+7
layout asp.net-mvc nested
source share
1 answer

Yes, layout overlays are possible. In fact, you just create a layout that uses the layout itself, since layouts are just views, there are no problems.

You pretty much do it the way you described:

_SubLayout.cshtml

 @{ Layout = "~/Views/Shared/_Layout.cshtml"; } @RenderBody() 

A few things to keep in mind:

  • The contents of the subpattern will be placed where you have @RenderBody in your base layout, as well as the contents of the view. Your sub-layout still needs its @RenderBody to determine where the contents of the view that uses it will be placed.

  • Any sections defined according to your base layout must be implemented in your layout, or Razor will throw an exception, just as if your view did not implement this section. For example:

    _Layout.cshtml

     @RenderSection("Foo", required: true) 

    _SubLayout.cshtml

     @section Foo { <p>Foo</p> } 
  • If your presentation should be able to implement a section (required or not), then its layout should determine. For example, in the above code, any view using _SubLayout.cshtml will not be able to define the Foo section because it will no longer exist. If you try, you will get an exception. To allow this view to define this section, you need to do something like the following:

    _SubLayout.cshtml

     @section Foo { @RenderSection("Foo", required: true) } 

    This defines the section for the purpose of the basic layout, and then allows the section to be allowed for any view that uses this layout.

In fact, there is a blog entry on my blog that touches on all this in much more detail if you need it: http://cpratt.co/how-to-change-the-default-asp-net-mvc-themet/

+10
source share

All Articles