Saturday, October 3, 2009

HttpUtility.ParseQueryString save the day...

Imagine when coding, you're getting a querystring as a parameter in string format with something like "studentid=1024&stateid=12&zipcode=90210&editmode=false". To manipulate the zip code value how would you normally do?

Guess what, I'll blindly do a string manipulation to get or update the value. This is inefficient (on second thought, I feel like I'm stupid). I just noticed that there's an easy way available in .NET Framework that will make my life easier. It's available since .NET Framework 2.0!!! HttpUtility.ParseQueryString definitely save me from headache.

Sample code:
    private void SomeFunction()
{
const string queryString = "studentid=1024&stateid=12&zipcode=90210&editmode=false";

// Parses a query string into a NameValueCollection using UTF8 encoding.
var collection = HttpUtility.ParseQueryString(queryString);

// Original value
Console.WriteLine("original value in string format : ");
Console.WriteLine("{0}", collection);

// Get existing value
Console.WriteLine("existing value : {0}", collection.Get("zipcode"));

// Set new value
collection.Set("zipcode", "10001");

// Display the new value
Console.WriteLine("updated value : {0}", collection.Get("zipcode"));

// Convert back to string
Console.WriteLine("value in string format");
Console.WriteLine("{0}", collection);
}
Here's the output:
    original value in string format :
studentid=1024&stateid=12&zipcode=90210&editmode=false
existing value : 90210
updated value : 10001
value in string format
studentid=1024&stateid=12&zipcode=10001&editmode=false
Press any key to continue . . .

2 comments:

  1. Interesting. I generally use Request.QueryString["studentid"] to retrieve querystring values; I've never had to modify them. But this is definitely good to know. Thanks.

    ReplyDelete
  2. Not only to modify them, there's a case when I'm getting the value in one long string. Parse it into NameValueCollection will make it much more easier to read the item value.

    ReplyDelete