Getting a value from the QueryString on the URL is simple and looks like this:
string value = Request.QueryString[”key”];
All it does it parse the QueryString looking for the first instance of “key“ and returns its value. But what if you were asked to actually implement Request.QueryString? How would you do it? Write some kind of string parser?
I was writing some code today and out of nowhere, I wondered how one would get all the values for every key of the same name from the QueryString. For example, if your QueryString had multiple values named “key”, such as http://localhost/myapp/details.aspx?key=1&key=2&key=3. I have no idea why you would do this, but it is allowed so theoretically I'm sure someone somewhere is doing this.
Anyway, I got off on a tangent and started writing some code to handle this. It's rather simple, but as I was writing it I realized I was close to actually implementing the Request.QueryString call, so I finished it and ended up with this:
using System.Collections.Specialized;
public static string GetQueryStringValue(string key)
{
NameValueCollection coll = HttpContext.Current.Request.QueryString;
string[] keys = coll.AllKeys;
for (int i = 0; i < keys.Length; i++)
{
if (keys[i].ToLower() == key.ToLower())
{
string[] values = coll.GetValues(i);
return values[0];
}
}
return string.Empty;
}
Some things to note:
-
The NameValueCollection class is found in System.Collections.Specialized.
-
coll.AllKeys returns all the keys in the QueryString, not just the set you are looking for.
-
coll.GetValues returns all the values for the set of keys you are looking for.
-
The above method just returns the first item in the value array, which is exactly what Request.QueryString does.
Print | posted on Thursday, November 11, 2004 10:50 AM