简体   繁体   中英

load different Layout component for Mobile and Desktop device on Blazor Server Application

I am developing a web application in Blazor Server that has different pages for mobile devices and desktop devices, so I can't just rely on CSS properties to differentiate page rendering. I would like that "App.razor" loads the correct layout depending on whether the user starts application from a mobile device or a desktop device. Is it possible? If so, how can I do?

the solution is very simple: In the App.razor

<CascadingAuthenticationState>
    <Router AppAssembly="@typeof(Program).Assembly" PreferExactMatches="@true">
        <Found Context="routeData">
            @if (isMobile)
            {
                <RouteView RouteData="@routeData" defaultLayout="@typeof(MainLayoutMobile)" />
            }
            else
            {
                <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
            }
        </Found>
        <NotFound>
            <LayoutView Layout="@typeof(MainLayout)">
                <p>Sorry, there is nothing at this address.</p>
            </LayoutView>
        </NotFound>
    </Router>
</CascadingAuthenticationState>

@code
{
    [Inject] protected IJSRuntime _JS { get; set; }
    protected bool isMobile = false;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            int innerWidth = await BrowserService.GetInnerWidth(_JS);

            if (innerWidth < 480)
               isMobile = true;
           else
               isMobile = false;

       }
    }
}

Where BrowserService is a service registered in Startup class:

public class BrowserService
{
    public static async Task<int> GetInnerWidth(IJSRuntime _JS)
    {
        return await _JS.InvokeAsync<int>("browser.getInnerWidth");
    }
}

and javascritp file:

window.browser = {

getInnerWidth: function () {
    return window.innerWidth;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM