I am using async/await, and calling an async method from one of my views and I need to wait until it finishes. I've seen a lot of examples for ASP.NET MVC, where you can just put an "async" into the signature of your action. But I haven't seen any examples for ASP.NET WebPages.
Do I just call "Wait()" on the returned task inside my Razor view? I've seen recommendations against Wait().
Please give me some references/examples on how to properly call async methods from within a Razor view in WebPages.
Don't call methods from within the view. The view should really just be binding to data that's on the model. If there's an asynchronous operation to be performed to fetch the model's data, perform it in the controller when populating the model.
As a contrived example:
and in the controller:
and in the view:
The model should essentially be "complete" when it's given to the view to render, and the view should just be rendering it. The asynchronous operations should be in the controller.
As an alternative to putting too much code in the controller and keeping it in the model, you can move an asynchronous operation to some kind of initialization on the model:
Then in your controller you'd invoke that:
Or perhaps an asynchronous factory on the model:
Then in the controller:
There are a number of ways to go about this, really. The main thing is to keep the asynchronous operations out of the view, whose only job should be to render the UI once the model is complete.