Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 355
Mason G. Zhwiti Avatar asked Sep 29 '11 19:09

Mason G. Zhwiti


People also ask

What is RenderSection in MVC?

@RenderSection is used for injecting content in the defined section. It allows you to specify a region in Layout. Two steps are there to define @RenderSection in ASP.NET MVC. A. Specify a @RenderSection Area in Layout Page.

What is use of RenderBody RenderSection and RenderPage in MVC?

A layout page can only contain one RenderBody method, but can have multiple sections. To create a section you use the RenderSection method. The difference between RenderSection and RenderPage is RenderPage reads the content from a file, whereas RenderSection runs code blocks you define in your content pages.

What is razor view in MVC with example?

Razor is a markup syntax that lets you embed server-based code into web pages using C# and VB.Net. It is not a programming language. It is a server side markup language. Razor has no ties to ASP.NET MVC because Razor is a general-purpose templating engine.


1 Answers

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.

like image 185
Erik Funkenbusch Avatar answered Sep 22 '22 16:09

Erik Funkenbusch