In Blazor how to call a function at Page Load (event name)?

Leave a Comment

 There are two main ways you can do this, and either will work. I tend to prefer the first, but the second also gets the job done.

The first way, is in your @code block, you can override the OnInitialized method. I use the async version as you can kick off your task and let the page basics load, and then it will refresh when it gets set up.

@code {

void SomeStartupMethod()
    // Do Some Work

Task SomeStartupTask()
    // Do some task based work
    return Task.CompletedTask;

protected override async Task OnInitializedAsync()
    await SomeStartupTask();

This will do work on the page load, like an initial service call to populate data, filling in lists conditionally, whatever you need to do. BTW, a trick I found is that if you put await Task.Delay(1); as the first line of the OnInitializedAsync method body, it will break the remaining execution free from the page render, so you can get an initial and responsive page while the initial load is still processing in the background. Just something to get your page responsive faster.

The second way is to override the OnAfterRender method, which allows the page 1 full render and then executes. It also has a default input of bool firstRender that you can use as a condition for data loads and other things.

protected override void OnAfterRender(bool firstRender)
    // execute conditionally for loading data, otherwise this will load
    // every time the page refreshes
        // Do work to load page data and set properties

The important thing to remember for this method is that it will execute any time the Blazor engine detects the need to refresh the UI, so use that firstRender parameter wisely.

Depending on what you need to do, different lifecycle methods can be useful at different times, and there are a few more I haven't touched on. For further info, take a look at the official docs. I've been able to get very far on my own just using what the docs have supplied, and this link will get you started at lifecycle methods.

Hope this helps!


Post a Comment

Note: only a member of this blog may post a comment.