Dan Herbert
Dan Herbert

Reputation: 103417

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

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?

Upvotes: 4

Views: 4477

Answers (4)

Pete Montgomery
Pete Montgomery

Reputation: 4100

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.

Upvotes: 5

ajma
ajma

Reputation: 12206

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

Upvotes: 0

Scott Dorman
Scott Dorman

Reputation: 42516

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:

Upvotes: 0

tvanfosson
tvanfosson

Reputation: 532465

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.

Upvotes: 3

Related Questions