The name 'Component' does not exist in the current context

2

I'm trying to create a view component to reuse on pages, I'm trying to follow some video tutorials. I have already installed via nuget the entire Microsoft.AspNetCore.Mvc, but when I try to call it from the viewpage, using

@Component.InvokeAsync("Componente")

I have the error

The name 'Component' does not exist in the current context.

I'musingVS2017,asp.netmvc5.Anyoneknowwhatmaybemissing?InstallsomethingelsethatIdonotknow?Orinmvc5isitotherwisethecomponentcall?

WhenIstarttypingComponentandpressingctrl+spaceshouldappearthelistofoptionsincludingtheComponentaccordingtothefollowingimage,notethatComponentisnotappearing:

    
asked by anonymous 06.06.2018 / 16:57

1 answer

3

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:

    
06.06.2018 / 19:06