I have default layout _Layout.cshtml for the most pages. However for some group of pages I would like to have slightly modified default layout. I know I could just copy that fil
Yes, layout inheritance is possible. Essentially, you're just creating a layout that itself utilizes a layout, since layouts are just views, there's no issues with that.
You pretty much do it exactly as you described:
_SubLayout.cshtml
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
@RenderBody()
A few things to keep in mind:
The content of the sub-layout will be placed where you have @RenderBody
in your base layout, just as the content of a view would be. Your sub-layout still needs its own @RenderBody
to determine where the content of the view that utilizes it should be placed.
Any sections defined as required in your base layout must be implemented in your sub-layout or Razor will raise an exception, just as if your view did not implement the section. For example:
_Layout.cshtml
@RenderSection("Foo", required: true)
_SubLayout.cshtml
@section Foo
{
<p>Foo</p>
}
If your view needs to be able to implement a section (required or not), the sub-layout must define it. For example, in the code above, any view using _SubLayout.cshtml
would not be able to define a Foo
section, because it would no longer exist. An exception would be raised if you tried. In order to allow that view to define that section you would have to do something like the following:
_SubLayout.cshtml
@section Foo
{
@RenderSection("Foo", required: true)
}
This defines the section for the purpose of the base layout and then allows the section to be defined by any view that uses this sub layout.
There's actually a post on my blog that goes into all this in much greater detail if you need it: http://cpratt.co/how-to-change-the-default-asp-net-mvc-themet/