Blazor uses the @page directive to associate a component with a specific route. When a user navigates to a URL, the Blazor router searches for a component with a matching @page directive and renders it.

Defining a Basic Route

@page "/create-blog"
<h3>Create Blog Post</h3>

In this example, when a user navigates to /create-blog, the associated component will be displayed.

Supporting Multiple Routes

You can also associate multiple routes with a single component by adding multiple @page directives:

@page "/create-blog"
@page "/blog/create"

This makes the component accessible via either route.

Routing Setup in App.razor

The App.razor file configures the routing system for your Blazor application:

<Router AppAssembly="@typeof(App).Assembly"> <Found Context="routeData"> <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" /> <FocusOnNavigate RouteData="@routeData" Selector="h1" /> </Found> <NotFound> <LayoutView Layout="@typeof(MainLayout)"> <h1>Page not found</h1> </LayoutView> </NotFound></Router>
  • The <Router> component is responsible for URL matching.
  • <RouteView> renders the component associated with the current route.
  • <NotFound> displays fallback UI if no route matches.

Navigating Programmatically in Blazor

To navigate to a route in code (e.g., after submitting a form), use the NavigationManager service:

@inject NavigationManager Navigation
<button @onclick="NavigateToHome">Go to Home</button>@code { void NavigateToHome() { Navigation.NavigateTo("/home"); }
}
  • NavigationManager.NavigateTo() is used for programmatic navigation.
  • You can also use options like forceLoad: true to reload the page.

Summary:

  • Use @page to map components to routes.
  • Configure the router in App.razor.
  • Navigate programmatically using NavigationManager.