'How can I transfer data from index.razor file to another razor file in C# blazor

I have a data in Index.razor from the database and now I am trying to get the data from Index.razor to other 2 razor files.

Can anyone let me know how can I do it

this is Serverside



Solution 1:[1]

Simplest way is to get your data out of your UI and into DI services.

Here's a simple demo.

MyDataService:

public class MyDataService
{
    public string MyMessage { get; set; } = string.Empty;

    private bool initialized;
    public async ValueTask GetData()
    {
        if (!initialized)
        {
           // emulate a async data get from a Db
            await Task.Delay(1000);
            MyMessage = $"Got data at {DateTime.Now.ToLongTimeString()}";
            this.initialized = true;
        }
    }
}

Registered in Program:

builder.Services.AddScoped<MyDataService>();

Used in Index.razor:

@page "/"
@inject MyDataService myData

<PageTitle>Index</PageTitle>

@if (loaded)
{
    <div class="p-2">
        MyData : @myData.MyMessage
    </div>
}

@code {
    private bool loaded;

    protected override async Task OnInitializedAsync()
    {
        await myData.GetData();
        loaded = true;
    }
}

And Counter.razor:

@page "/counter"
@inject MyDataService myData

<PageTitle>Counter</PageTitle>

<h1>Counter</h1>

<p role="status">Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@if (loaded)
{
    <div class="p-2">
        MyData : @myData.MyMessage
    </div>
}


@code {
    private int currentCount = 0;
    private bool loaded;

    protected override async Task OnInitializedAsync()
    {
        await myData.GetData();
        loaded = true;
    }

    private void IncrementCount()
    {
        currentCount++;
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MrC aka Shaun Curtis