I have a URL that also might have a query string part, the query string might be empty or have multiple items.
I want to replace one of the items in the query string or add it if the item doesn't already exists.
I have an URI object with the complete URL.
My first idea was to use regex and some string magic, that should do it.
But it seems a bit shaky, perhaps the framework has some query string builder class?
set('PARAM_HERE', VALUE_HERE); history. pushState(null, '', url); This will preserve everything about the URL and only change or add the one query param. You can also use replaceState instead of pushState if you don't want it to create a new browser history entry.
To pass in parameter values, simply append them to the query string at the end of the base URL. In the above example, the view parameter script name is viewParameter1.
The value of a parameter can be updated with the set() method of URLSearchParams object. After setting the new value you can get the new query string with the toString() method. This query string can be set as the new value of the search property of the URL object.
The value of Request. QueryString(parameter) is an array of all of the values of parameter that occur in QUERY_STRING. You can determine the number of values of a parameter by calling Request. QueryString(parameter).
I found this was a more elegant solution
var qs = HttpUtility.ParseQueryString(Request.QueryString.ToString());
qs.Set("item", newItemValue);
Console.WriteLine(qs.ToString());
Lets have this url:
https://localhost/video?param1=value1
At first update specific query string param to new value:
var uri = new Uri("https://localhost/video?param1=value1");
var qs = HttpUtility.ParseQueryString(uri.Query);
qs.Set("param1", "newValue2");
Next create UriBuilder
and update Query
property to produce new uri with changed param value.
var uriBuilder = new UriBuilder(uri);
uriBuilder.Query = qs.ToString();
var newUri = uriBuilder.Uri;
Now you have in newUri
this value:
https://localhost/video?param1=newValue2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With