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:
- Inject instance of ICompositeViewEngine to layout page
- If partial view exists that generate mark-up where it’s included
- 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.
@if (Engine.FindView(ViewContext, "_LeftMenu", isMainPage: false).Success)
<partial name="_LeftMenu" />
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" />
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.
View Comments (1)
Thanks for sharing this! Great timing as I'm about to start a project that will need dynamically added partial views.