简体   繁体   中英

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

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++;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM