I get this error when I use view component
Asked Answered
E

1

5

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")
Eneidaenema answered 19/9, 2021 at 18:18 Comment(0)
G
8

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);
}
Groceries answered 19/9, 2021 at 18:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.