Search code examples
.net-corelayoutblazor

How to change the default layout in blazor once it set in App.razor?


In my application I am planning to set two layouts. BeforeLoginLayout and AfterLoginLayout. As of now , in App.Razor, I set the defaultLayout as BeforeLoginLayout. I would like to change the default layout after user logged into application. How to do this in Blazor ? I can set it in individual page. I would like to avoid this and set as the default layout.


Solution

  • Here's some code and a demo page which shows how to change out the layout dynamically. You should be able to adapt this to fit your requirement.

    Modify App as follows:

    <Router AppAssembly="@typeof(Program).Assembly" PreferExactMatches="@true">
        <Found Context="routeData">
            <CascadingValue Value="this">
                <RouteView RouteData="@routeData" DefaultLayout="this.LayoutType" />
            </CascadingValue>
        </Found>
        <NotFound>
            <LayoutView Layout="@typeof(MainLayout)">
                <p>Sorry, there's nothing at this address.</p>
            </LayoutView>
        </NotFound>
    </Router>
    
    @code {
    
        private Type LayoutType = typeof(MainLayout);
    
        public void SetLayout(Type layout)
        {
            if (layout != LayoutType)
            {
                this.LayoutType = layout;
                StateHasChanged();
            }
        }
    }
    

    This demo page then shows how to change out the layouts dynamically. OtherLayout is a copy of MainLayout with something to differentiate it.

    @page "/"
    
    <div class="m-2 p-2">
        <button class="btn btn-secondary" @onclick="() => ButtonClick(typeof(MainLayout))">Main Layout</button>
        <button class="btn btn-dark ms-2" @onclick="() => ButtonClick(typeof(OtherLayout))">Other Layout</button>
    </div>
    
    
    @code {
    
        [CascadingParameter] public App MyApp { get; set; }
    
    
        void ButtonClick(Type layoutType)
        {
            MyApp.SetLayout(layoutType);
        }
    }