In MVC Razor, how do you do a RenderSection define

2019-01-26 05:32发布

问题:

I have a top-level _Layout.cshtml that looks something like this:

<html>
<head>
    @RenderSection("Header", required: false)
</head>
<body>

    @RenderSection("LeftPane", required: false)
    @RenderSection("RightPane", required: false)
    @RenderBody()

</body>
</html>

Then I have two "sub-layouts." One defines just the LeftPane section, the other defines both a LeftPane and a RightPane. These sub-layouts are called _LeftPane.cshtml and _LeftPlusRightPane.cshtml, and they have Layout set to "_Layout.cshtml."

Then in each View .cshtml file, I set the Layout to either _LeftPane.cshtml or _LeftPlusRightPane.cshtml, depending on what I want to show up on the page.

That all works fine. The problem is with the new "Header" section I've added in the <head> portion of the document. This section is not defined in the sub-layouts, but rather in the actual Views. When I try to view something this way, I get the error:

The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_LeftPlusRightPane.cshtml": "Header".

I don't want to render the Header section in the sublayouts, I want to render it up in the _Layout.cshtml file. How do I "pass through" the defined Header section from the low level view, through the sub-layouts, up to the top _Layout?

回答1:

You can nest layouts. So _Layout2 has Layout = "_Layout.cshtml";

You can also use _ViewStart files in each of your View subfolders to specify a different default layout for that subfolder.

To "pass through" the section, you just do something like this:

@section Header {@RenderSection("Header", false)}

That allows you to pass content up the chain.