Tuesday, 29 November 2011

Checking QueryString in ASP using JavaScript

The QueryString object appears to act in a very odd manner when using JavaScript as your ASP language. The main problem with it is that you cannot check to see if a query string parameter is missing using undefined; it simply does not work.

As an example, say your script has been called with no parameter; now check to see if the parameter name is present in the QueryString object like this: if (Request.QueryString("name") == undefined) {...} - this will evaluate to false, even though name has not been defined. It also does not evaluate to null, 0, or the empty string.

The only way I have been able to discover to evaluate this is to use the Count method. for example:
var myvar = Request.QueryString("name");
if (myvar.Count === 0) {myvar = ""; }

This will work correctly.