2

When I have a url like:

http://www.mysite.com/?MyTest=

MyTest shows up as a key in the querystring of the request object.

If I remove the = sign like:

http://www.mysite.com/?MyTest

It no longer shows up in the querystring keys (or AllKeys if you prefer).

How can I determine whether this key exists or not?

Mike Cheel
  • 12,626
  • 10
  • 72
  • 101

3 Answers3

4

This is quite odd behaviour, without the = sign the QueryString object returned by the Request has a Count of 1 with a value of MyTest and a key of null.
You could test the QueryString to see if it contains the value you are expecting:

if(Request.QueryString.ToString().Contains("MyTest"))
{
    // Do stuff
}

Edit: this answer gives a bit more explanation as to what is going on with keyless parameters (scroll past the accepted answer).

Community
  • 1
  • 1
Andy Rose
  • 16,770
  • 7
  • 43
  • 49
  • 1
    Since the contains method is case-sensitive, you might want to convert the strings to upper for comparison. Request.QueryString.ToString().ToUpper().Contains("MYTEST") – DaveB Mar 08 '12 at 17:22
  • 1
    The proper way based on the answer from the edit is `(Request.QueryString.GetValues(null) ?? new string [0]).Contains("MyTest")` – eitanpo Jun 14 '12 at 12:58
1

I believe you can do Request.QueryString[null] or Request.QueryString.GetValues(null).


Without the equal sign MyTest is no longer a key, but a key-less value, you use null to get those. To check for both cases do this:
bool myTestPresent = Request.QueryString["MyTest"] != null
   || Request.QueryString.GetValues(null).Contains("MyTest", StringComparer.OrdinalIgnoreCase);
Max Toro
  • 28,282
  • 11
  • 76
  • 114
0

You shoul use ToString() function

if (Request.QueryString.ToString() == "MyTest")
{
 //do something
}
Yuri Fedoseev
  • 539
  • 5
  • 7