X

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.

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.

Liked this post? Empower your friends by sharing it!
Categories: ASP.NET

View Comments (1)

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

Related Post