Reputation: 73
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?
Upvotes: 0
Views: 2513
Reputation: 73
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;
}
}
Upvotes: 3