Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

asp.net mvc - In MVC Razor, how do you do a RenderSection defined below a sub-layout?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...