user1017882
user1017882

Reputation:

Are there any methods to help me manipulate the query string parameters?

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.

Upvotes: 1

Views: 278

Answers (3)

Rich O'Kelly
Rich O'Kelly

Reputation: 41757

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));
}

Upvotes: 0

Grzegorz Gierlik
Grzegorz Gierlik

Reputation: 11232

Probably you are looking for HttpUtility.ParseQueryString().

Upvotes: 1

s_nair
s_nair

Reputation: 812

 HttpUtility.ParseQueryString(queryString);

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

Upvotes: 2

Related Questions