Alexan
Alexan

Reputation: 8637

blazor server query string: how to get data only one time

On blazor page we need to get data from query string.

We use OnInitialized event to read data:

Working with Query Strings in Blazor

for example:

protected override void OnInitialized()
    {
        var uri = NavManager.ToAbsoluteUri(NavManager.Uri);
        if (QueryHelpers.ParseQuery(uri.Query).TryGetValue("initialCount", out var _initialCount))
        {
            currentCount = Convert.ToInt32(_initialCount);
        }
    }

But we use prerendering:

@(await Html.RenderComponentAsync<App>(RenderMode.ServerPrerendered))

and this code executes two time.

It's a problem, because we need to reach database with these parameters, but we don't want to do it twice.

Disable prerendering is not an option.

Tried to move code to other events, for example to OnParametersSet, but it executes twice too.

Maybe we can check it event executes first or second time and use this condition?

Or some other options?

Upvotes: 1

Views: 1153

Answers (1)

MrC aka Shaun Curtis
MrC aka Shaun Curtis

Reputation: 30185

I don't think there's a safe way to do this in .Net5 - you've tagged your Question with .Net5.

.Net6 adds persist-prerendered-state, which I think will solve your problem. Here's a link to the MS-Docs page that explains how to use it:

MS-Docs - Persist prerendered state

Upvotes: 2

Related Questions