I have a _ViewStart defining the master layout for my project (header, footer).
In this project, I have several Areas. Every area has the same header and footer, plus its own side menu. For that, I created a _ViewStart on the root dir of that area. Here is the (simplified) code:
/Views/_ViewStart.cshtml
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
/Views/Shared/_Layout.cshtml
<html>
<div>
//header
</div>
<div>
@RenderBody
</div>
</html>
Area Foo -> /Areas/Foo/Views/_ViewStart.cshtml
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="row">
<div class="sidemenu">
//default sidemenu for this area
</div>
<div>
@RenderBody()
</div>
</div>
The page /Areas/Foo/Views/Bar/Index.cshtml won't render and I get this error:
CS0103: The name 'RenderBody' does not exist in the current context
How to achieve this kind of master page nesting?
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.
_Viewstart. cshtml is used to place common UI logic across the Views in the folder, where it is located. This means, the views in a single folder which is having _Viewstart. cshtml will be rendered along with it.
Add MVC Area with Visual StudioIn Solution Explorer, right click the project and select ADD > New Scaffolded Item, then select MVC Area.
To add a new Area, Right Click on application name from solution explorer -> Select Add -> Select New Scaffolded Item -> select MVC Area from middle pane of dialog box -> Enter Name of Area -> Click Ok.
I hate to answer my own question, but here it goes:
You can't reference the site's root _ViewStart directly on the _ViewStart of your area if you want a RenderBody there.
So the solution is:
/Views/_ViewStart.cshtml references /Views/Shared/_MainLayout.cshtml
/Areas/Foo/Views/_ViewStart.cshtml references /Areas/Foo/Views/Shared/_AreaLayout.cshtml
/Areas/Foo/Views/Shared/_AreaLayout.cshtml references /Views/Shared/_MainLayout.cshtml
And that's it. You have to use the "Shared" folder to have the method "RenderBody()" available.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With