Mahyar
Mahyar

Reputation: 1

A view component named 'Search' could not be found

I have a runtime error with this message

InvalidOperationException: A view component named 'Search' 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'.

Controller:

public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;

    public HomeController(ILogger<HomeController> logger)
    {
        _logger = logger;
    }

    public IActionResult Index()
    {
        return View();
    }
 }

enter image description here

Upvotes: 0

Views: 1777

Answers (1)

mj1313
mj1313

Reputation: 8459

The code you provide has nothing done with the ViewComponent. Have you created the Search ViewComponent?

For how to create a viewcomponent, usually you can follow the below steps.

1.Create a folder named ViewComponents in the root path, then create the ViewComponent class (SearchViewComponent). Note, it must end with ViewComponent.

public class SearchViewComponent : ViewComponent
{
    public async Task<IViewComponentResult> InvokeAsync()
    {
        
        return View();
    }
}

2.Add a folder named Components under Views > Shared folder, and add a folder named Search(corresponding to your ViewComponent class) under Components folder, then create the View, you can simply name it as Default.cshtml.

Default.cshtml:

For test, I simply set this in the View:

<h2>Search Content</h2>

enter image description here

3.Use the following to call ViewComponent:

@await Component.InvokeAsync("Search")

Example:

Home Index View:

@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Learn about <a href="https://learn.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>

@await Component.InvokeAsync("Search")

Result:

enter image description here

For more details, refer to the offical document.

Upvotes: 1

Related Questions