Home > Software engineering >  I get this error when I use view component
I get this error when I use view component

Time:09-22

I am new to ASP.NET Core. I get this error when I use view component. Thank you for your help

InvalidOperationException: Method 'Invoke' of view component 'UI.ViewComponents.NavbarViewComponent' cannot return a Task.

This is my code

public async Task<IViewComponentResult> Invoke()
{
    var settings = await _db.Settings.ToListAsync();
    return View(settings);
}

And in view :

@await Component.InvokeAsync("Navbar")

CodePudding user response:

When you are returning a task from the View Component, you should use the InvokeAsync , asynchronous method instead of the sync method. Your Code Should look like this :

public async Task<IViewComponentResult> InvokeAsync()
{
  var settings = await _db.Settings.ToListAsync();
  return View(settings);
}
  • Related