In your case the problem is why View Components is an appeal lodged at MVC 6 and Asp.Net 5 and its application is actually a MVC5 with Asp.Net 4
Below is an example of the implementation in Dotenetcore (reference).
First create a directory, at the root of your MVC application, called Componentsview and add a new class called ComponenteViewComponent
that must inherit from ViewComponent
public class ComponenteViewComponent : ViewComponent
{
public async Task<IViewComponentResult> InvokeAsync()
{
return View();
}
}
If you do not respect the suffix Viewcomponent the MVC will not recognize it as such and maybe there may be your first problem. If you created the class by calling only Componente
, you need to add an annotation so that the component is recognized by that name.
[ViewComponent(Name = "Componente")]
public class Componente : ViewComponent
{
public async Task<IViewComponentResult> InvokeAsync()
{
return View();
}
}
Note the points above and after creating the class, go to the directory /Views/Shared/, add the directory Components and inside it another folder called Component, which is the name of its component.
Inside the folder Component add to PartialView
calling for Default
, my example I just added the following html snippet:
<h1>Olá eu sou um componente</h1>
Finally its structure must be like this:
Now, in any view of your site you can invoke your component, in my case I added the snippet at the top of Homecontroller’s Index view:
<div>
@await Component.InvokeAsync("Componente")
</div>
And that’s the result:
What version of Asp.net? If I’m not mistaken, ViewComponent is available from mvc core 1.1
– Leandro Angelo
dotnet --version 2.1.4
– Jonas Centenaro