Is it possible to conditionally display partial views in _Layout.cshtml?

Suppose I have _Layout.cshtml, where I render the left sidebar, which is common to every page of my site. Something in this direction - a menu, for example

<div id="left-sidebar">
    @Html.Action("_MenuView", "LeftSideMenu")
</div>

The function that I would like to add is to add another partial view, but only display it in certain sections of the website.

For example, on a blog, I can display a list of message categories or a tree structure for posts.

<div id="left-sidebar">
    @Html.Action("_MenuView", "LeftSideMenu")

    @if ("???")
    {
        @Html.Action("_BlogTreeView", "BlogEntries")
    }
</div>

How could I do this? I know that I want to display "_BlogTreeView" if the view I'm viewing is returned by BlogController ... where can I go from there?

+5
source share
1 answer

In your layout add this section

@RenderSection("blogEntries", false)

Then in each view where you want to show a partial view, add this:

@section blogEntries {
    @Html.Action("_BlogTreeView", "BlogEntries")
}
+8
source

All Articles