Mariusz Jamro Mariusz Jamro - 3 months ago 50
C# Question

How to check if view component exists before rendering in razor view in ASP.NET Core

ASP.NET Core has the View Components mechanism for reusing parts of views. You can include the view component in a razor template file using

Component.InvokeAsync
call:

@await Component.InvokeAsync("MyComponent", new { data = 1 })


If view component with given name doesn't exist an
InvalidOperationException
exception is thrown.

InvalidOperationException: A view component named 'MyComponent' could not be found.


I would like to know how can i check if view component exist before rendering in razor view. Ideally something like:

@if (Component.Exists("MyComponent")
{
@await Component.InvokeAsync("MyComponent", new { data = 1 })
}
else
{
<p>Component not found</p>
}

Answer

You can inject IViewComponentSelector into your view to check if component exists:

@inject Microsoft.AspNetCore.Mvc.ViewComponents.IViewComponentSelector selector

@if (selector.SelectComponent("MyComponent")!= null)
{
    @await Component.InvokeAsync("MyComponent", new { data = 1 })
}
else
{
    <p>Component not found</p>
}
Comments