blazorblazor-server-side.net-8.0page-lifecycle

Blazor server - how to prevent page render on the layout level


I have a Blazor Server app in .net8. There are many pages that share common parameter in the route, have common base page and layout:

PageA

@page "/{folder}/files
@inherits MyBasePage

<div>@folderModel.Files</div>

PageB

@page "/{folder}/users
@inherits MyBasePage

<div>@folderModel.Users</div>

Base page

MyBasePage {
  [Parameter]
  public string folder { get; set; }

  protected FolderModel folderModel { get; private set; }

  protected override async Task OnInitializedAsync()
  {
    await base.OnInitializedAsync();
    folderModel = await someService.GetFolderData(folder);
  }
}

It may happen that a folder object is deleted from the system and I want to display a "Not found" content in this case. How can do it and in general prevent rendering/initializing all pages (A, B, ...) when folderData is not found (null)? I tried adding some logic around this to the Layout:

...
if (folderWasFound)
{
  @Body
}
else
{
  <div>Folder not found</div>
}
...

but I still need to add if (folderModel is not null) ... to all pages to prevent null reference errors. The folderWasFound is shared from page to layout via scoped service. Also Layout's OnInitializedAsync seems to be executed after the page's OnInitializedAsync (which I can understand). Are there any other alternatives that will save me all the ifs in pages A,B,...?

I know I can intercept route values (folder in this case) in the Layout initialization itself, but still the initialization order makes it useless.


Solution

  • Throw an exception when the folder is NotFound and setup an <ErrorBoundary> at some higher level (maybe MainLayout).