June 20, 2022 10:12 by
Peter
In this article, we are going to discuss route parameters in Blazor. A route parameter is defined in the URL by wrapping its name in a pair of {braces} along with @page declaration.
Example; @page “/employee/{employeeId}
For this tutorial I’m using Microsoft Visual Studio Community 2022 (64-bit) – Preview with Version 17.2.0 Preview 5.0.
Parameter value capture
Value of a parameter can be captured by simply adding a property with the same name and decorating it with an attribute [Parameter]
[Parameter]
public string FruitCode { get; set; }
For demo purposes, I’m using the Counter.razor component in which I am adding three anchor tags with parameter value
<li><a href="/counter/Orange">Orange</a></li>
<li><a href="/counter/Mango">Mango</a></li>
<li><a href="/counter/Apple">Apple</a></li>
The route will look like below
@page "/counter"
@page "/counter/{FruitCode}"
Here {FruitCode} is the parameter
When you click on Orange – the value “Orange” will be passed as parameter in the URL
If you look at the image, in the address bar, you can see that “Orange” has been passed and the same has been displayed as “Selected Fruit: Orange”. The entire code from Counter.razor component has been given below for reference.
@page "/counter"
@page "/counter/{FruitCode}"
<PageTitle>Counter</PageTitle>
<h1>Counter</h1>
<p role="status">Current count: @currentCount</p>
<p role="banner"> Selected Fruite : @FruitCode</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
<h1>Select a Fruit</h1>
<ul>
<li><a href="/counter/Orange">Orange</a></li>
<li><a href="/counter/Mango">Mango</a></li>
<li><a href="/counter/Apple">Apple</a></li>
</ul>
@code {
private int currentCount = 0;
[Parameter]
public string FruitCode { get; set; }
private void IncrementCount()
{
currentCount++;
}
}
Note
As we are navigating to the same page,
The component will not be destroyed before navigation.
OnInitialized lifecycle methods will not be executed.
Route Parameter Constraints
To define a constraint for a parameter it is suffixed with a colon and then the constraint type. For example, :int will only match the component’s URL if it contains a valid integer value in the right position.
The route looks like below
@page "/counter"
@page "/counter/{CurrentCount:int}"
Please refer to the Microsoft documentation for more details.
Thank you for reading my article. Please leave your comments in the comment box below.