Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Async Property in Razor page

I am trying to bring up a simple .NET Core 2.0 Web Application with Razor pages. The page is connected to an equally simple Core 2.0 Web API. I have a simple class:

public class About : PageModel
{
    private ServiceProxy serviceProxy;

    public About(ServiceProxy serviceProxy)
    {
        this.serviceProxy = serviceProxy;
    }

    public IEnumerable<ProductViewModel> Values { get; set; }

    public async void OnGetAsync()
    {
        this.Values = await this.serviceProxy.GetValuesAsync();
    }
}

And the page is also simple:

@page
@model About
@{
    ViewData["Title"] = "About";
}
<h2>@ViewData["Title"]</h2>
<h3>@Model.Message</h3>
@foreach (var product in @Model.Values)
{
    <p>@product.Name</p>
}

However, the page displays before the OnGetAsync() method can populate the 'Values' list. This seems like such a common operation, but I can't find any discussion of it (I've also tried iterating over an async 'GetValues()' method).

How are CSHTML pages supposed to interact with a Web API that may take a few seconds to return results?

like image 261
Quarkly Avatar asked May 21 '18 15:05

Quarkly


People also ask

How do you call a method in Razor pages?

Razor pages have handler-methods which are HTTP verbs. So to call a method from your page you need to put On followed by the http verb you want then your method name . And in your view pass the name to the asp-page-handler without the OnPost or OnGet prefix or Async suffix.

Can Page_load be async?

In page life cycle, when Page_load gets fired, ASP.NET finds it async and when it reaches to await, it releases the current thread and a new thread is picked from the thread pool to continue the activity and the call the web service took place asynchronously.

Is Cshtml a Razor?

All Razor files end with . cshtml. Most Razor files are intended to be browsable and contain a mixture of client-side and server-side code, which, when processed, results in HTML being sent to the browser. These pages are usually referred to as "content pages".

What is ViewData in Razor?

ViewData is a container for data to be passed from the PageModel to the content page. ViewData is a dictionary of objects with a string-based key. You add items to ViewData as follows: public class IndexModel : PageModel. {


1 Answers

That is because of the async void, which is basically a fire and forget, and should be avoided. The page will load before the function has time to complete as they will be executing in parallel.

Change the signature to async Task so that the Page can await the action to complete.

public async Task<IActionResult> OnGetAsync() {
    this.Values = await this.serviceProxy.GetValuesAsync();
    return Page();
}

Reference Introduction to Razor Pages in ASP.NET Core

like image 172
Nkosi Avatar answered Nov 02 '22 22:11

Nkosi