I have been able to find information about using layouts in ASP.NET Core MVC 6 but not for this specific scenario. I know that it is possible for one view to use a layout and another view to use a different layout.
Is it possible for one view to use two layouts? For example, one layout has a horizontal nav bar on the top and another layout has a vertical nav bar on the left, so the view would show both a top and left nav bar. I can probably just combine the .cshtml code into a second layout file but I’d like to know if we can simply assign two layouts.
2
Answers
You can create two different layouts and then load required layout in _ViewStart.cshtml via conditional statement.
To directly answer your question, no you cannot do that in fact, your specific view has no control over the layout page because specific page render within a layout page by using @RenderBody()
Therefore, @RenderBody() would be displying your view page as this would be within your layout page so no direct way to call two layout at the same time.
But other than, @RenderBody() within layout yes you can use multiple layout page within a singlee page or view.
Based on your scenario and description, what you can do is, create a layout with couple of other secregated layout. In other words, you can build a layout within multiple content section.
For instance: you can create a section for hearder, another for footer and so on just like what partial view does and using @RenderSection() you can combine them. Then you can call @RenderBody() within it.
Note: You can check our official document for details implementation here.
Apart of above implementaion, you can render your page using different layout either through _ViewStart.cshtml page or using direct reference from that particular page.
Let’s assume you have following layout page:
Hence, you can either do following:
Directly Define with your page:
Or Write Conditional On _ViewStart.cshtml:
Pass Layout Name In controller:
Once you pass your layout name within ViewData["page"] which one you want to render it will decide within _ViewStart.cshtml.
Takeaways:
To meet your requirement, you can use partial view and then render partial within the same layout you want your view page to be displayed. This would the ideal solution.
Resolve your scenario:
Let’s assume you have two seperate layout which have their own design of nav bar or anything and now you want to bind them within a single view page, therefore, you can do as following:
Now within your view page you can do as following:
Note: As you can see, I have using two layout within a single page using partial tag helper we can use multiple layout within a single page. Hope noww you can meet your requirement and now you know both ways.
Output: