{{announcement.body}}
{{announcement.title}}

Conditionally Include Partial View in ASP.NET Core

DZone 's Guide to

Conditionally Include Partial View in ASP.NET Core

A developer demonstrates how to use view injection to create a left-hand menu that will only appear in our application when it is needed.

· Web Dev Zone ·
Free Resource

I have an ASP.NET Core web application where I need to include a 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 to conditionally include a partial view in an ASP.NET Core layout page.

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

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

  1. Inject an instance of ICompositeViewEngine into the layout page.
  2. If a partial view exists it will generate mark-up where it's included.
  3. If a partial view doesn't exist then it will be left out.

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

@inject ICompositeViewEngine Engine

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

<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 the need for a different mark-up if a partial view is present. Without this need, things get easier. There's no need to inject anything to the layout page and we can use the partial tag helper optional-parameter.

Wrapping Up

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

Topics:
web dev ,asp.net core tutorial ,c# tutorial ,web application development

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}