Search code examples
blazormaui

How to declare global variables in Blazor


How to declare global variables in Blazor , for example I have inputquestions in Index I want to use this in another page called Quiz. https://github.com/KalyanAllam/MauiAppMCQs/

@page "/"
<h1>  Quiz </h1>
Select Input Questions and 
Click on  Quiz  .
<div class="row">
    <p>Questions:</p>
    <input type="range" min="5" max="20" step="5" @bind="@inputquestions"
     @bind:event="oninput" />
</div>
<p>@inputquestions</p>
@code {
    public  int inputquestions=5;
}


Solution

  • Be aware that any "global" stuff is for "all users". What "all users" means heavily depends on interactivity mode you choose.

    • Blazor wasm (and maui): Your static class or singleton is for the one user only and you are safe to use both
    • Blazor Server (and SSR): Don't use static classes and singletons for keeping user related data.

    Static classes

    public static class MyStaticClass
    {
      public int InputQuestions {get;set;} =5;
    }
    
    <input type="range" min="5" max="20" step="5" @bind="@MyStaticClass.InputQuestions"
         @bind:event="oninput" />
    
    

    Or a service

    public MyClass
    {
    public int InputQuestions {get;set;} =5;
    }
    
    //program.cs
    builder.Services.AddSingleton<MyClass>();
    
    
    @inject MyClass myClass
    ...
    @bind="@myClass.InputQuestions"
    

    For a difference between these two, look for Singleton vs Static class