In your case the problem is because View Components is a feature featured in MVC 6 and Asp.Net 5 and your application is in fact 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 named ComponenteViewComponent
which must inherit from ViewComponent
public class ComponenteViewComponent : ViewComponent
{
public async Task<IViewComponentResult> InvokeAsync()
{
return View();
}
}
If you do not respect the ViewComponent suffix, MVC will not recognize it as such, and there may be your first problem there. If you created the class by calling only Componente
, you need to add an annotation for the component to be recognized by that name.
[ViewComponent(Name = "Componente")]
public class Componente : ViewComponent
{
public async Task<IViewComponentResult> InvokeAsync()
{
return View();
}
}
Note the above points and after creating the class, go to the / Views / Shared / directory, add the Components directory and a folder called < in> Component , which is the name of your component.
In the Component folder, add the PartialView
named Default
, my example I added only the following html snippet:
<h1>Olá eu sou um componente</h1>
Finally your structure should look like this:
Now,inanyviewofyoursiteyoucaninvokeyourcomponent,inmycaseIaddedtheexcerptatthetopoftheHomeControllerviewindex:
<div>@awaitComponent.InvokeAsync("Componente")
</div>
And the result is this: