Wednesday, January 23, 2008

Modifying Query String in .net



Sometimes we need to modify the query string values of URL.

For Example :

Consider our Current URL is : http://www.mysite.com/MyHomePage.aspx?Value=x
and, we want to change it as : http://www.mysite.com/MyHomePage.aspx?Value=y

We can access all the Query Strings from Request.QueryString["query_string_name"], but we can't make any modification to QueryString["query_string_name"] because it is read only. What we can do is, copy that Query String collection to an instance of System.Collections.Specialized.NameValueCollection and replace the current query string from URL.

The following code will change the query string value of "Value" to y.
System.Collections.Specialized.NameValueCollection queryStrings = System.Web.HttpUtility.ParseQueryString( Request.QueryString.ToString());
queryStrings.Set("Value", "y");
lnkNew.NavigateUrl = Request.Url.AbsolutePath + "?" + queryStrings.ToString();


This code will set the navigation URL of lnkNew(hyper link) as "http://www.mysite.com/MyHomePage.aspx?Value=y".

We need to specify the "?" between path and query string parameters.

We can add add query string value using NameValueCollection.Add("","") method. Eg: In above example, we are going to add new query string value using following code:
System.Collections.Specialized.NameValueCollection queryStrings = System.Web.HttpUtility.ParseQueryString( Request.QueryString.ToString());
queryStrings.Set("Value", "y");
queryStrings.Add("Value2", "MyName");
lnkNew.NavigateUrl = Request.Url.AbsolutePath + "?" + queryStrings.ToString();


Above code segment will set the navigation URL to.
http://www.mysite.com/MyHomePage.aspx?Value=y&Value2=MyName

"&" will appear default between two parameters.

We can also redirect to another page with modified query string parameters.

System.Collections.Specialized.NameValueCollection queryStrings = System.Web.HttpUtility.ParseQueryString( Request.QueryString.ToString());
queryStrings.Set("Value", "y");
queryStrings.Add("Value2", "MyName");
string page="Contact.aspx"
Response.Redirect(page + "?" + queryStrings.ToString());


This code will redirect our page to
http://www.mysite.com/Contact.aspx?Value=y&Value2=MyName


We can also remove the query string value.
For example
queryStrings.Remove("Value");

The "Value" parameters from the query string.