'A view component named 'PreviewCV' could not be found
I have created a view component.
public class PreviewCVComponent : ViewComponent
{
..
public async Task<IViewComponentResult> InvokeAsync(int id)
{
return View();
}
}
I have added a folder into views/shared/components which is given the name PreviewCV. Under that folder I have added a view called Default.cshtml.
The Component is called from another view. Which is located under views/CV, and has the name CV.cshtml.
I am trying to call the component with the use of
@await Component.InvokeAsync("PreviewCV", new { id = -1 })
This results in:
InvalidOperationException: A view component named 'PreviewCV" 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'.
I am using .net core.
Solution 1:[1]
--In Models folder
FileName: TestViewComponent.cs
--In TestViewComponent class
[ViewComponent(Name = "TestViewComponent")] //Solution
public class TestViewComponent: ViewComponent
{
public IViewComponentResult Invoke()
{
return View();
}
}
Put ViewComponent in suffix solve the problem.
Solution 2:[2]
Using net core 5.0, class name (e.g. PreviewCV) can either be written as PreviewCV OR PreviewCVViewComponent
so
public class PreviewCV : ViewComponent
and
public class PreviewCVViewComponent : ViewComponent
will work fine while below will generate error (same as shown in question)
public class PreviewCVComponent : ViewComponent
Also noticed that attribute didn't have any effect on these
[ViewComponentAttribute]
Solution 3:[3]
One solution is to call it like:
@await Component.InvokeAsync(typeof(PreviewCVComponent), new { id = -1 })
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Diego Venâncio |
| Solution 2 | Muhammad Waqas Iqbal |
| Solution 3 | BRap |
