Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ViewComponent and InvokeAsync method

In the following method I'm getting the warning: This async method lacks 'await' operators and will run synchronously. Where can I use await in this mehod? Note: This method is returning a simple static View without interacting with a Database etc.

public class TestViewComponent : ViewComponent
{
    public async Task<IViewComponentResult> InvokeAsync()
    {
        return View();
    }
}
like image 272
nam Avatar asked Oct 12 '16 20:10

nam


People also ask

What is ViewComponent?

View components are similar to partial views, but they're much more powerful. View components don't use model binding, they depend on the data passed when calling the view component. This article was written using controllers and views, but view components work with Razor Pages.

How do you use ViewComponent?

Create the view component Razor viewCreate the Views/Shared/Components/PriorityList folder. This folder name must match the name of the view component class, or the name of the class minus the suffix. If the ViewComponent attribute is used, the class name would need to match the attribute designation.

How to Invoke a view component?

In a View, you can invoke a view component one of two ways: use a View's Component property or add a Tag Helper to the View. For my money, the simplest method is to simply call the InvokeAsync method from the View's Component property, passing the name of your view component and its parameters.


1 Answers

Since you have no asynchronous work to do, you could remove the async qualifier and just return Task.FromResult:

public Task<IViewComponentResult> InvokeAsync()
{
  return Task.FromResult<IViewComponentResult>(View());
}

Alternatively, you could just ignore the warning (i.e., turn it off with a #pragma).

like image 176
Stephen Cleary Avatar answered Sep 24 '22 03:09

Stephen Cleary