tags:

views:

201

answers:

4

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?

A: 

I've always been generating them myself.

string url = Request.UrlReferrer.PathAndQuery;

(url[url.Length - 1] != '?' ? "?" : "&") + Url.Encode(key) + "=" + Url.Encode(key)
  • Url.Encode is something in ASP.NET MVC
ajma
Just FYI, your code will only work if the string ENDS in a '?' character. The example I gave in my question will not work with that code. It will add another '?' character to the URL.
Dan Herbert
I made an update. Give that a try.
ajma
+3  A: 

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.

tvanfosson
Be careful about doing somethings like 'builder.Query += "hello=world"', the UriBuilder seems to give you extra ? separators each time you use +=.
Frank Schwieterman
A: 

If you're using the ASP.NET MVC Framework release, I believe there is a TabBuilder object that will allow you to do that. Otherwise you can use a UriBuilder, but you will still have to do some of the parsing yourself. There are some utility classes online as well, but I've never used them so I don't know how well they work:

Scott Dorman
+2  A: 

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.

Pete Montgomery
Just what I needed, thanks. UriBuilder has got some weird/unexpected behaviors but these extensions methods did what I want and worked as I expected.
Frank Schwieterman