Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blazor - Bind query strings to a dictionary

I have a page with a table and dynamic filters in it. When a filter changes, I need to redirect to the current page with a new or updated query parameter. For example, if I'm in the /users route and the name "John" is being searched, I need to redirect to /users?name=john. If I want to see all Johns with application role, I need to redirect to /users?name=john&hasRole=true and so on. The reason for this is that a search result must be reproducible by sharing the URL.

I need all query parameters as a Dictionary<string, string>. How can I bind all query parameters to a Dictionary<string, string> in Blazor WASM?

like image 982
Parsa99 Avatar asked Apr 21 '26 07:04

Parsa99


2 Answers

Chris Sainty has a nice post on working with query strings in blazor but essentially you'll need the NavManager and Microsoft.AspNetCore.WebUtilities and then you can use the ParseQuery method to get a dictionary of the query string params:

    protected override void OnInitialized()
    {
        var uri = NavManager.ToAbsoluteUri(NavManager.Uri);
        if (QueryHelpers.ParseQuery(uri.Query).TryGetValue("initialCount", out var _initialCount))
        {
            currentCount = Convert.ToInt32(_initialCount);
        }
    }
like image 52
Brandon Pugh Avatar answered Apr 23 '26 23:04

Brandon Pugh


If you know what filters you are applying, you define the query parameters as component parameters (using Brandon's counter example in the other answer).

@page "/counter"
@inject NavigationManager NavManager

<PageTitle>Counter</PageTitle>

<h1>Counter</h1>

<p role="status">Current count: @CurrentCount</p>

<button class="btn btn-primary" @onclick="() => IncrementCount(1)">Increment</button>

<button class="btn btn-primary" @onclick="() => IncrementCount(50)">Count plus 50</button>

@code {
    [Parameter, SupplyParameterFromQuery] public int CurrentCount { get; set; } = 0;

    private void IncrementCount(int value)
        => NavManager.NavigateTo($"/counter?CurrentCount={CurrentCount + value}");
}
like image 36
MrC aka Shaun Curtis Avatar answered Apr 23 '26 22:04

MrC aka Shaun Curtis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!