Search code examples
blazorblazor-server-sideblazor-webassembly

How to pass a value from a page to the layout in Blazor?


I have a layout (MainLayout.razor), and it has a flag called ShowFooter. On some pages, I want to be able to set that flag to true, and on some others to false.

I haven't been able to find any clear instructions on how a page (i.e. a component with a route) can communicate with its layout. How could/should this be done in Blazor?

Note: You might suggest creating 2 layouts, one with and one without the footer, but that wouldn't really solve my problem, I want to be able to show and hide the footer at different times on the same page. Plus, this is just one scenario where there is a need to communicate between the layout and the page. There are also countless others, to which such workarounds might not even be applicable.


Solution

  • The simplest way to do that is to define a public Boolean property named ShowFooter in the MainLaout component, as follows:

    public bool ShowFooter {get; set;}
    

    And to cascade a reference to MainLaout component to given components, by wrapping the markup within a CascadingValue component whose Value attribute is set to this, like this:

    @inherits LayoutComponentBase
    
    
    <CascadingValue Value="this">
         <div class="sidebar">
            <NavMenu />
        </div>
        <div class="main">
             <div class="content px-4">
                @Body
            </div>
        </div>
    </CascadingValue>
    @code
    {
        public bool ShowFooter {get; set;}
    
         protected override void OnInitialized()
        {
          // Put here code that checks the value of ShowFooter and acts in 
          // accordance with your dear wishes
    
         }
    }
    

    Usage in Index.razor

    @code{
         // Gets a reference to the MainLayout component
        [CascadingParameter]
        public MainLayout Layout { get; set; } 
    
        protected override void OnInitialized()
        {
            Layout.ShowFooter= true;
        
        }
    }