I\'m curious what everyone does for handling/abstracting the QueryString in ASP.NET. In some of our web apps I see a lot of this all over the site:
int val = 0;
Here's what I came up with. It uses generics to return a strongly-typed value from the QueryString or an optional default value if the parameter isn't in the QueryString:
///
/// Gets the given querystring parameter as a the specified value
///
/// The type to convert the querystring value to
/// Querystring parameter name
/// Default value to return if parameter not found
/// The value as the specified , or the default value if not found
public static T GetValueFromQueryString(string name, T defaultValue) where T : struct
{
if (String.IsNullOrEmpty(name) || HttpContext.Current == null || HttpContext.Current.Request == null)
return defaultValue;
try
{
return (T)Convert.ChangeType(HttpContext.Current.Request.QueryString[name], typeof(T));
}
catch
{
return defaultValue;
}
}
///
/// Gets the given querystring parameter as a the specified value
///
/// The type to convert the querystring value to
/// Querystring parameter name
/// The value as the specified , or the types default value if not found
public static T GetValueFromQueryString(string name) where T : struct
{
return GetValueFromQueryString(name, default(T));
}
Since writing this post I've written a very small class library for manipulating querystring values - see https://github.com/DanDiplo/QueryString-Helper