Blazor WebAssembly - Get Query String Parameters with Navigation Manager
Built with ASP.NET Core Blazor WebAssembly 3.2.1
This is a quick post to show how you can add a couple of simple extension methods to the NavigationManager
class in your Blazor WebAssembly app for accessing query string parameters in the URL.
Query String Extension Methods for Navigation Manager
The below extension methods use the HttpUtility.ParseQueryString()
method to uri into a name value collection.
The first method returns the entire query string as a NameValueCollection
that can then be accessed like an array (e.g. querystring["id"]
), and the second method returns a single query string value.
using Microsoft.AspNetCore.Components;
using System;
using System.Collections.Specialized;
using System.Web;
namespace BlazorApp.Helpers
{
public static class ExtensionMethods
{
// get entire querystring name/value collection
public static NameValueCollection QueryString(this NavigationManager navigationManager)
{
return HttpUtility.ParseQueryString(new Uri(navigationManager.Uri).Query);
}
// get single querystring value with specified key
public static string QueryString(this NavigationManager navigationManager, string key)
{
return navigationManager.QueryString()[key];
}
}
}
Blazor get whole query string collection
This is how to get the entire querystring collection from the navigation manager and then get a single value from the collection.
var querystring = NavigationManager.QueryString();
// get id from query string
var id = querystring["id"];
Blazor get single value from query string
This is how to get a single querystring value directly from the navigation manager in one step.
var id = NavigationManager.QueryString("id");
Subscribe or Follow Me For Updates
Subscribe to my YouTube channel or follow me on Twitter, Facebook or GitHub to be notified when I post new content.
- Follow me on Twitter at https://twitter.com/jason_watmore
- Subscribe on YouTube at https://www.youtube.com/JasonWatmore
- Follow me on Facebook at https://www.facebook.com/JasonWatmoreBlog
- Follow me on GitHub at https://github.com/cornflourblue
- Feed formats available: RSS, Atom, JSON
Other than coding...
I'm currently attempting to travel around Australia by motorcycle with my wife Tina on a pair of Royal Enfield Himalayans. You can follow our adventures on YouTube, Instagram and Facebook.
- Subscribe on YouTube at https://www.youtube.com/TinaAndJason
- Follow us on Instagram at https://www.instagram.com/tinaandjason
- Follow us on Facebook at https://www.facebook.com/TinaAndJasonVlog
- Visit our website at https://tinaandjason.com.au
Need Some Blazor Help?
Search fiverr to find help quickly from experienced Blazor developers.