Blazor accessing global variable issue

Haviv Elbsz 1,966 Reputation points
2023-10-01T07:18:17.1633333+00:00

Hi all I asked here how to save variable state and i get long answers and what I want is to know if it's possible in blazor to define a variable somewhere in the app structure so I can access it from any component. something like in console program variable in the main method. Thank you very much

Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,425 questions
{count} votes

Accepted answer
  1. Tiny Wang-MSFT 1,831 Reputation points Microsoft Vendor
    2023-10-02T03:46:02.3266667+00:00

    We could use Cascading values and parameters to achieve the global variable feature, we could define the cascading value in the root(MainLayout component) so that we could use it in any other child components.

    I followed the document to have codes like below.

    @inherits LayoutComponentBase
    
    <div class="page">
        <div class="sidebar">
            <NavMenu />
        </div>
    
        <main>
            <div class="top-row px-4">
                <a href="https://docs.microsoft.com/aspnet/" target="_blank">About</a>
            </div>
            <CascadingValue Value="@golbalVaule">
                <article class="content px-4">
                    @Body
                </article>
            </CascadingValue>
        </main>
    </div>
    
    @code{
        GolbalValue golbalVaule = new GolbalValue { id = 1, name = "user1" };
    
    }
    

    and this is my index component.

    @page "/"
    
    <PageTitle>Index</PageTitle>
    
    <h1>Hello, world!</h1>
    
    Welcome to your new app.
    
    <SurveyPrompt Title="How is Blazor working for you?" />
    
    <div>@golbalValue.name</div>
    
    @code{
        [CascadingParameter]
        public GolbalValue? golbalValue { get; set; }
    }
    

    User's image

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful