Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace item in querystring

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?

like image 502
Karsten Avatar asked Apr 21 '09 12:04

Karsten


People also ask

How can I add or update a query string parameter?

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.

How do you pass a value in QueryString?

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.

How do I change the parameters in a URL?

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.

What is request QueryString ()?

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).


2 Answers

I found this was a more elegant solution

var qs = HttpUtility.ParseQueryString(Request.QueryString.ToString());
qs.Set("item", newItemValue);
Console.WriteLine(qs.ToString());
like image 162
Chris Avatar answered Sep 30 '22 06:09

Chris


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

like image 32
psulek Avatar answered Sep 30 '22 07:09

psulek