Conditionally include partial view in ASP.NET Core

I have ASP.NET Core web application where I need to include partial view only if it exists. The application uses areas and some areas may have their specific side menu. This blog post shows two ways how to conditionally include partial view to ASP.NET Core layout page.

My goal was to do it the easiest way possible by using out-of-box things and making sure I don’t create ugly looking mess. I wanted to avoid all kind of additional classes to wrap dirty secrets away from controllers and views.

Product and main page with left menu if it exists

As it turns out it is actually easy thing to do thanks to view injection in ASP.NET Core. Here’s how to do it:

  1. Inject instance of ICompositeViewEngine to layout page
  2. If partial view exists that generate mark-up where it’s included
  3. If partial view doesn’t exist then leave it out.

I added the following line of code to the very beginning of layout page.

@inject ICompositeViewEngine Engine

Then I replaced RenderBody() method in layout page with following block of Razor.

<div class="row">
    @if (Engine.FindView(ViewContext, "_LeftMenu", isMainPage: false).Success)
    {
        <div class="col-md-3">
            <partial name="_LeftMenu" />
        </div>
        <div class="col-md-9">
            @RenderBody()
        </div>
    }
    else
    {
        <div class="col-md-12">
            @RenderBody()
        </div>
    }
</div>

In my case there was need for different mark-up if partial view is present. Without this need things get even easier. There’s no need to inject anything to layout page and we can use optional-parameter of partial tag helper.

<partial name="_LeftMenu" optional="true" />

Wrapping up

Before inventing custom code components to achieve something on ASP.NET Core it is good idea to see what framework provides out-of-box. This blog post introduced how to conditionally include partial view to ASP.NET Core layout page. With view injection we got view engine instance to layout page to check if partial view exists. Based on this we generated markup to show page with or without left menu.

Gunnar Peipman

Gunnar Peipman is ASP.NET, Azure and SharePoint fan, Estonian Microsoft user group leader, blogger, conference speaker, teacher, and tech maniac. Since 2008 he is Microsoft MVP specialized on ASP.NET.

    One thought on “Conditionally include partial view in ASP.NET Core

    • April 4, 2019 at 12:09 am
      Permalink

      Thanks for sharing this! Great timing as I’m about to start a project that will need dynamically added partial views.

    Leave a Reply

    Your email address will not be published. Required fields are marked *