Tuesday, February 1, 2011

append values into querystring in asp.net

If you try to add "&" directly into string , it doesn't work
Ex: WebPage.aspx?Var1=DVal1&Var2=DVal2

if u want to create above querystring & u try to write statement as below
string url="WebPage.aspx?Var1=" + DVal1 + "&Var2=" + DVal2;
DVal1 & DVal2 are strings. It will work for simple cases but it won't work for few cases.
If DVal1 & DVal2 contains space in contents (DVal1="my value") It will show you
WebPage.aspx?Var1=my.
to make proper querystring you have to use a Server.UrlEncode

It replaces space with %20 and & with %26
string url="WebPage.aspx?Var1=" + Server.UrlEncode(DVal1) + "&Var2=" + Server.UrlEncode(DVal2);

Use of Server.UrlEncode avoids error and help us to append data to querystring.

Happy Coding!! 

No comments:

Post a Comment