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