By Endy Tjahjono. Last update 01 Jun 2021.
Here is my brain dump when reviewing Blazor WebAssembly’s router using the features of more established routers like UI-Router and Vue Router.
Inside component / razor pages, using @page directive. Example:
@page "/product"
Be careful of two components handling the same route.
Avoid route path with dot.
Meaning: http://localhost/#/product instead of http://localhost/product.
Not available.
In URL path:
@page "/product/{ProductID:int}"
<h1>Product @ProductID</h1>
@code {
[Parameter]
public int ProductID { get; set; }
}
Optional parameter is not supported.
There is a OnParametersSetAsync event to detect parameter change.
No built-in support for parameters in query string. Need to parse yourself during NavigationManager.LocationChanged (not async!). A helper is available in Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery.
<NavLink href="product" Match="NavLinkMatch.Prefix">Product</NavLink>
How to create link with route parameter? Concatenate them yourself :)
<NavLink href=@($"product/{4}")>Product 4</NavLink>
Path construction relies on the <base href="/"> tag in wwwroot/index.html.
@inject NavigationManager NM
<button @onclick="GoTo4">Go</button>
@code {
private void GoTo4()
{
NM.NavigateTo($"product/{4}");
}
}
Some helpers available in NavigationManager: Uri, BaseUri, ToAbsoluteUri, ToBaseRelativePath.
NotFound tag inside Router tag inside App.razor file
<Router AppAssembly="@typeof(Program).Assembly" PreferExactMatches="true">
<Found Context="routeData">
<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
</Found>
<NotFound>
<LayoutView Layout="@typeof(MainLayout)">
<p>Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
@page "/product/{*astringvar}"
@code {
[Parameter]
public string astringvar { get; set; }
}
Manually call NavigateTo within OnInitialized:
@page "/"
@inject NavigationManager NM
@code {
protected override void OnInitialized()
{
NM.NavigateTo("/product");
}
}
To prevent user refreshing the browser, changing the browser url, pressing link when there is unsaved change, etc.
No built-in support.
None. Probably in the future.
Nope. Flat routes.
Just NavigationManager.LocationChanged?
There is no oncomplete onabort beforeRouteEnter beforeRouteUpdate.
None?