Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to add a key/value to an existing URL string?

Tags:

c#

.net

asp.net

I want to generate a link on my page where a key/value pair is added to the URL dynamically so that:

Default.aspx?key1=value1

Becomes:

Default.aspx?key1=value1&key2=value2

So that the existing query retains any keys in the URL. Also, if there are no keys, then my key would be added, along with the '?' since it would be needed.

I could easily write some logic that does this, but this seems like something that the framework should have a utiltity for. Is there any way to add keys to a query string without writing my own logic for it?

like image 540
Dan Herbert Avatar asked Mar 02 '23 01:03

Dan Herbert


2 Answers

I know, it's strange this is not supported properly in the .NET Framework. A couple of extensions to UriBuilder will do what you need though.

like image 97
Pete Montgomery Avatar answered Mar 03 '23 15:03

Pete Montgomery


You can use the UriBuilder class. See the example in the Query property documentation. FWIW, ASP.NET MVC includes the UrlHelper class that does exactly this sort of thing for the MVC framework. You might want to think about adding an extension method to the HttpRequest class that takes a dictionary and returns a suitable Url based on the given request and the dictionary values. This way you'd only have to write it once.

like image 43
tvanfosson Avatar answered Mar 03 '23 15:03

tvanfosson