Search code examples
c#asp.net.net-corerazor-pages

Razor pages: How to wait for page´s model to load the info before presenting the web page


I need to resolve a little problem. I am building a website and one page in particular (Razor pages project) let´s call it "Results.cshtml" needs to wait for its page model (Results.cshtml.cs) to gather the information from a SQL server before printing it. So the page model would do all the queries in its "OnGet()" method.

The problem is that the web page loads before the data is received on the page´s model and I keep on getting an object null reference exception (because the data is not yet there).

If I add a @Thread.Sleep(2000) to the web page, then it renders just fine because it gives time to the SQL to send the info. So it is clear that the solution is to find a way so that the page awaits for the model to gather the data. But I could not find it.

ModelPage's OnGet method:


public void OnGet()
        {
            GetPage();
        }
private async void GetPage()
        {
            Task<string> message = _pagesService.GetPagesByAuthorIDAsync("user01");

            var options = new System.Text.Json.JsonSerializerOptions { PropertyNameCaseInsensitive = true };
            Pages = System.Text.Json.JsonSerializer.Deserialize< List<WebPage> >(await message, options);
        }

I need the property: "Pages" to have received the data before printing the Page.

The Page looks like this:


@page
@model MyPageModel
@using System.Threading;

@{
    //Thread.Sleep(2000);
}


<div> @Model.Pages[0].Name </div>

Thanks a lot!

PD: For some strange reason it does not let me add a "Hello everyone!" at the beginning. Weird, so here it goes "Hello everyone!!"


Solution

  • You need to await the async method, and ideally return Tasks, not void:

    public async Task OnGetAsync()
    {
        await GetPage();
    }
    private async Task GetPage()
    {
        Task<string> message = _pagesService.GetPagesByAuthorIDAsync("user01");
    
        var options = new System.Text.Json.JsonSerializerOptions { PropertyNameCaseInsensitive = true };
        Pages = System.Text.Json.JsonSerializer.Deserialize< List<WebPage> >(await message, options);
    }