Search code examples
c#asp.net-coreasp.net-core-viewcomponent

ViewComponent must have one public method named 'InvokeAsync' or 'Invoke' - ASP.NET CORE (.NET 6)


I am now designing a website using .NET6 and unlike older versions of ASP.NET Core, this version doesn't have methods like @{Html.RenderPartial("_ViewNamePartial")} so I'm using ViewComponents but when I try to render it, it throws an error :

InvalidOperationException: View component 'aquaWeb.ViewComponents.ProductCardViewComponent' must have exactly one public method named 'InvokeAsync' or 'Invoke'.

Here is my code:

Parent page that calls ViewComponent :

<html>
    <body>
        <div class="row">
            <div class="col-md-9">
                @await Component.InvokeAsync("ProductCard");
            </div>
        </div>
    </body>
</html>

View Component :

public class ProductCardViewComponent : ViewComponent
    {
        public async Task<IViewComponentResult> InvokeAsync()
        {
            return await Task.FromResult((IViewComponentResult)View());
        }
        public IViewComponentResult Invoke()
        {
            return View();
        }
    }

Solution

  • So apparently the error was :

    ViewComponent must have ONLY one public method named InvokeAsync or Invoke

    ViewComponent wants exactly just one method, not much or less.

    Going to read more careful next time...

    I changed my ViewComponent class from this :

    public class ProductCardViewComponent : ViewComponent
        {
            public async Task<IViewComponentResult> InvokeAsync()
            {
                return await Task.FromResult((IViewComponentResult)View());
            }
            public IViewComponentResult Invoke()
            {
                return View();
            }
        }
    

    To this:

    public class ProductCardViewComponent : ViewComponent
        {
            public async Task<IViewComponentResult> InvokeAsync()
            {
                return await Task.FromResult((IViewComponentResult)View());
            }
        }
    

    and it's working pretty well