Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a URL input parameter value to Blazor page?

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?

like image 375
001 Avatar asked Dec 12 '19 06:12

001


2 Answers

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.

like image 63
enet Avatar answered Oct 16 '22 19:10

enet


It's in the doc : components routing

like image 22
agua from mars Avatar answered Oct 16 '22 18:10

agua from mars