Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ViewComponent not found in Asp.NET Core 2.2 using Razor Pages

I have created a very simple view component (/ViewComponents/MenuViewComponent.cs):

namespace MySite.ViewComponents
{    
    public class MenuViewComponent : ViewComponent
    {
        public Task<IViewComponentResult> InvokeAsync()
        {
            return Task.FromResult((IViewComponentResult)View("Default"));
        }
    }
}

The view part is here (/Pages/Components/Menu/Default.cshtml):

<div>Menu</div>

I am invoking the Menu from the _Layout.cshtml file like this:

@await Component.InvokeAsync("MenuViewComponent");

When viewing a page I get the following error message:

InvalidOperationException: A view component named 'MenuViewComponent' could not be found.
A view component must be a public non-abstract class, not contain any generic parameters, 
and either be decorated with 'ViewComponentAttribute' or have a class name ending with the 'ViewComponent' suffix. 
A view component must not be decorated with 'NonViewComponentAttribute'.

Question:
What am I missing to get this working?

like image 755
Chau Avatar asked Aug 31 '25 22:08

Chau


1 Answers

Make sure component view is in the search path as described in the following

Reference View components in ASP.NET Core

and also when calling the component just use the name without the suffix

@await Component.InvokeAsync("Menu") 
like image 134
Nkosi Avatar answered Sep 03 '25 13:09

Nkosi