Reputation: 545
I am working on a Blazor PWA that guides the user through the process and collects data. I wrote the class MyData and create an object of it, where the first data is collected. But actually I want the object to be created on startup. Here is, what I have so far and what works:
MyApp/Csharp/MyData.cs
namespace MyApp.Csharp
{
public class MyData
{
public decimal Data1 { get; set; } = -99.9m;
}
}
MyApp/Pages/Input.razor
@using MyApp.Csharp
@code{MyData myData = new(); }
<div>
<input type="number" @bind="myData.Data1" />
</div>
How can I create myData
at startup? I tried to move MyData myData = new();
in Main() but that resulted in the error "The name myData does not exist in the current context". I also created a file App.razor.cs and placed the code there but that also did not work with the same error message.
Upvotes: 0
Views: 331
Reputation: 36
If you only need a single instance for the whole PWA, the best solution is a static class.
public static class MyData
{
public static string MyData1;
}
In the PWA I am building, I use static classes for global data too. You can set the properties in the Main method in Program.cs before the first page is rendered.
If loading the data that you want to store in the class takes a long time, like calling a Web API, you should not load it in Program.cs but in the OnAfterRender (when firstRender is true) of the Index page (the main page of the PWA). Ideally you have to show some kind of notification that loading is in progress.
Upvotes: 1