Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I have/chain more than 1 _Layout pages in MVC 3? for a cshtml page?

I have a layout page and some pages that use it. But I want to implement a navigation control on some of the sub-pages that use it. So I want to use another nested layout page. Is this possible?

like image 300
Exitos Avatar asked Oct 31 '11 21:10

Exitos


People also ask

Can we have multiple layout pages in MVC?

Q. Can we use multiple Layout pages in a single MVC application? Yes, we can use multiple Layout in ASP.Net MVC application. By default, Visual Studio adds a Layout page in a shared folder which can be used by other View pages if required.

Can we have multiple _ViewStart in MVC?

We can also create multiple _ViewStart. cshtml pages. The file execution is dependent upon the location of the file within the folder hierarchy and the view being rendered. The MVC Runtime will first execute the code of the _ViewStart.

What is the purpose of the _layout Cshtml file in the pages shared folder?

Layout pages are typically named _Layout. cshtml, the leading underscore preventing them from being browsed directly. Standard practice is to specify the layout page in a _ViewStart. cshtml file, which affects all content pages in the folder in which it is placed, and all subfolders.

What is _layout Cshtml in MVC?

The file "_Layout. cshtml" represents the layout of each page in the application. Right-click on the Shared folder in Solution Explorer then go to "Add" item and click on "View". Now the View has been created.


2 Answers

Yes, it works great. Just tell your layout page to use another layout page

@{ Layout = "pathToMyOtherLayout"; }

You can also use sections to pass through to the parent layouts. For example:

@Section Headers {@RenderSection("Headers")}
like image 179
Erik Funkenbusch Avatar answered Oct 10 '22 02:10

Erik Funkenbusch


You can chain pages just like you can Master Pages, in _ViewStart.cshtml you will see how the layout page is defined:

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

You can just add this section in the _Layout.cshtml to reference another parent, or add it to an individual view to reference a different layout view.

ScottGu has a post with more info on Razor Layouts

I use this exact method for what you are talking about on some ecommerce sites, where you are in the checkout process I do not want any distractions (navigation, etc) within the view, so instead of having some special case if checkout in layout, I make a LayoutBrandingOnly and a Layout which "inherits" from it so I don't have to repeat all the branding html.

like image 38
Paul Tyng Avatar answered Oct 10 '22 02:10

Paul Tyng