How to pass a URL input parameter value to Blazor page?
Solution 1
A public property defined within a component, and annotated with the Parameter attribute serves the purpose of either storing a Component parameter passed to a child component from its parent component, as for instance, the following code pass a string parameter from a parent component to its child component.
ParentComponent.razor
<ChildComponent Title="I'm a child component" />
ChildComponent.razor
<p>@Title</p>
@code{
Public string Title { get; set; } = "Default Title";
}
or, storing the value of a route data, as for instance, the route data Start in the url https://localhost:44396/counter/123, which is automatically done by the framework, if you define a public property named Start, and annotate it with the Parameter attribute:
Counter.razor
@page "/counter"
@page "/counter/{start:int}"
<h1>Counter</h1>
<p>Current count: @Start</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
[Parameter]
public int Start { get; set; }
private void IncrementCount()
{
Start++;
}
}
Note that the definition of the Counter component contains two route templates. The first route template is set to use the default value of the Start property; that is the value 0. But the user can change the default value by providing a route parameter in the url, as for instance: https://localhost:44396/counter/123. Now when the button is clicked, the start value is 123, not 0. Just for the record, the second template contains a route constraint, which constrain the app to only work with int values.
Solution 2
It's in the doc : components routing
Related videos on Youtube
001
Only questions with complete answers are accepted as solutions.
Updated on September 16, 2022Comments
-
001 over 1 year
This passes a value into a blazor component
[Parameter] public string Id { get; set; }
But what about passing a value from the URL input parameter?
-
001 over 4 yearsrouting does not work in mainlayout? :) only in a razor component!
-
Henk Holterman over 4 years@001 - if that is the problem then you need to ask a much better question.