Monday, 24 February 2014

WindowsPhone 8 - Using "&" ampersand in QueryString Parameter

If you have "&" ampersand or any other url-reserved characters like "?" as part of your querystring paramter value, you will have to encode the value before passing it to the other page.

In .NET you can use the framework helper method HttpUtility.UrlEncode to encode the string containing "&" and in the target Page use the HttpUtility.UrlDecode helper method.

In windows phone the same helper methods are available in namespace System.Net.HttpUtility.

An alternate option is to use the Silverlight Uri.EscapeUriString and Uri.EscapeDataString

Usage:
//To Escape:
string encodedValue = Uri.EscapeDataString("William&Shakespeare");
NavigationService.Navigate(new Uri("/Page2.xaml?author=" + encodedValue, Urikind.Relative));

//To Unescape:

string encodedValue = NavigationContext.QueryString["author"];
string author = Uri.UnescapeDataString(encodedValue);

No comments:

Post a Comment