Reputation:
if(Page.Request.QueryString["ParamName"] != null)
if(Page.Request.QueryString["ParamName"] == expectedResult)
//Do something spectacular
The above seems cludgey. Is there a more elegant/compact way of checking if a query string parameter is not null and if so - retrieving the value of it?
Upvotes: 10
Views: 23968
Reputation: 16257
I thought first of offering
if ((Page.Request.QueryString["ParamName"] ?? "") == expectedResult) {
but quickly realized that with strings, comparing some string with null is fine, and will produce false, so really just using this will work:
if(Page.Request.QueryString["ParamName"] == expectedResult)
//Do something spectacular
Upvotes: 10
Reputation: 16812
I personally would go with a simple set of extension methods, something like this:
public static class RequestExtensions
{
public static string QueryStringValue(this HttpRequest request, string parameter)
{
return !string.IsNullOrEmpty(request.QueryString[parameter]) ? request.QueryString[parameter] : string.Empty;
}
public static bool QueryStringValueMatchesExpected(this HttpRequest request, string parameter, string expected)
{
return !string.IsNullOrEmpty(request.QueryString[parameter]) && request.QueryString[parameter].Equals(expected, StringComparison.OrdinalIgnoreCase);
}
}
and a sample usage
string value = Page.Request.QueryStringValue("SomeParam");
bool match = Page.Request.QueryStringValueMatchesExpected("SomeParam", "somevaue");
Upvotes: 2
Reputation: 13150
You can use String.IsNullOrEmpty
String.IsNullOrEmpty(Page.Request.QueryString["ParamName"]);
Or
var parm = Page.Request.QueryString["ParamName"] ?? "";
if(parm == expectedResult)
{
}
Upvotes: 7