1

At the moment I'm using all sorts of if statements and substrings in order to manipulate the query string parameters and wanted to know if there was a more efficient way of doing it.

To be precise - I'm needing to add a query string parameter to the current url but if it already exists - I need to just amend it.

To clarify - I CAN achieve this using standard string manipulation methods, and I know how to retrieve the current url etc. I'm just wondering if these wheels are already in place and I'm re-inventing them.

  • Manipulate from which language? Javascript or C#? – John Gathogo Jun 21 '12 at 09:25
  • 1
    Have a look at this link you might get the answer or alternate http://stackoverflow.com/questions/68624/how-to-parse-a-query-string-into-a-namevaluecollection-in-net – HatSoft Jun 21 '12 at 09:27

3 Answers3

2
 HttpUtility.ParseQueryString(queryString);

For more: http://msdn.microsoft.com/en-us/library/system.web.httputility.parsequerystring.aspx

s_nair
  • 812
  • 4
  • 12
1

Probably you are looking for HttpUtility.ParseQueryString().

Grzegorz Gierlik
  • 11,112
  • 4
  • 47
  • 55
0

You could parse the query string as a Dictionary<string,string> and use this to manipulate and then simply format the key value pairs as appropriate when outputting as a query string once more:

public Dictionary<string, string> ToDictionary(string queryString)
{
    return queryString.TrimStart('?').Split('&').Select(qp => qp.Split(',')).ToDictionary(a => a[0], a=> a[1]);
}

public Dictionary<string, string> ToString(Dictionary<string, string> queryString)
{
    return '?' + string.Join('&', queryString.Select(kvp => kvp.Key + '=' + kvp.Value));
}
Rich O'Kelly
  • 41,274
  • 9
  • 83
  • 114