Check if unassigned variable exists in Request.QueryString
Request.QueryString
is a NameValueCollection
, but items are only added to it if the query string is in the usual [name=value]*
format. If not, it is empty.
If your QueryString
was of the form ?test=value
, then Request.QueryString.AllKeys.Contains("test")
would do what you want. Otherwise, you're stuck doing string operations on Request.Url.Query
.
I wrote an extension method to solve this task:
public static bool ContainsKey(this NameValueCollection collection, string key)
{
if (collection.AllKeys.Contains(key))
return true;
// ReSharper disable once AssignNullToNotNullAttribute
var keysWithoutValues = collection.GetValues(null);
return keysWithoutValues != null && keysWithoutValues.Contains(key);
}
I use this.
if (Request.Params["test"] != null)
{
//Is Set
}
else if(Request.QueryString.GetValues(null) != null &&
Array.IndexOf(Request.QueryString.GetValues(null),"test") > -1)
{
//Not set
}
else
{
//Does not exist
}
Request.QueryString.GetValues(null)
will get a list of keys with no values
Request.QueryString.GetValues(null).Contains("test")
will return true