Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I conditionally render partial views in _Layout.cshtml?

Suppose I have a _Layout.cshtml where I render a left sidebar, which is common to every page of my website. Something along these lines - a menu, for example

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

A feature I would like to have would be to add another partial view, but only display it in certain sections of the website.

For example, in the blog section I may want to display a list of post categories or a treeview of the posts.

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

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

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

like image 685
Evgeny Avatar asked Mar 11 '13 22:03

Evgeny


People also ask

How do I render a partial part of a view?

Rendering a Partial View You can render the partial view in the parent view using the HTML helper methods: @html. Partial() , @html. RenderPartial() , and @html. RenderAction() .

Which is the way to render partial view using MVC Razor engine?

RenderPartial function to render Partial View in ASP.Net MVC Razor. The data will be fetched from database using Entity Framework and then the Partial View will be rendered using the @Html. RenderPartial function in ASP.Net MVC Razor.


1 Answers

In your layout, add this section

@RenderSection("blogEntries", false)

Then in every view where you want to show the partial view add this:

@section blogEntries {
    @Html.Action("_BlogTreeView", "BlogEntries")
}
like image 146
Andy Refuerzo Avatar answered Sep 23 '22 15:09

Andy Refuerzo