Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using _ViewStart on areas for nested content

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?

like image 478
andrecarlucci Avatar asked Feb 16 '12 18:02

andrecarlucci


People also ask

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 _ViewStart Cshtml?

_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.

How to add areas in MVC?

Add MVC Area with Visual StudioIn Solution Explorer, right click the project and select ADD > New Scaffolded Item, then select MVC Area.

How to add area in. net Core?

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.


1 Answers

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.

like image 170
andrecarlucci Avatar answered Oct 06 '22 09:10

andrecarlucci