It’s common to set values using the query string. For instance, it can contains search parameters and default values for a form. It also allows very useful for sharing a URL to specific resources.

Blazor doesn’t provide a way to get the values of the query string and bind them to properties. However, you can get the full URL using the NavigationManager and the right event in the Blazor component lifecycle to set the properties when needed.

The final code looks like:

@page "/"
@inject NavigationManager NavigationManager

<div>@Value</div>
<button type="button" @onclick="UpdateValue">Update value</button>

@code
{
    // πŸ‘‡ The value is set from the query string by the SetParametersAsync method
    [QueryStringParameter]
    public int Value { get; set; }

    public override Task SetParametersAsync(ParameterView parameters)
    {
        πŸ‘‡ Read the value of each property decorated by [QueryStringParameter] from the query string
        this.SetParametersFromQueryString(NavigationManager);

        return base.SetParametersAsync(parameters);
    }

    private void UpdateValue()
    {
        Value = new Random().Next();

        // πŸ‘‡ Update the URL to set the new value in the query string
        this.UpdateQueryString(NavigationManager);
    }
}

First, you need to create the QueryStringParameterAttribute attribute to decorate the properties to bind from the query string:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class QueryStringParameterAttribute : Attribute
{
    public QueryStringParameterAttribute()
    {
    }

    public QueryStringParameterAttribute(string name)
    {
        Name = name;
    }

    /// <summary>Name of the query string parameter. It uses the property name by default.</summary>
    public string Name { get; }
}

#blazor #.net #asp.net core #web

Binding parameters from the query string in a Blazor component
8.45 GEEK