Search

Monday, October 12, 2009

Useful Function for Type Casting Your Query String Values in ASP.NET

Whenever you want to get the query string value in ASP.NET, you usually use Request.QueryString. However, that always gives you a string value that is not type cast to the variable you want. So instead of an integer or a Guid, you always get a string. Here is little function that addresses that and gives you the proper type based on the variable type passed in. It’s used as follows:
' Declare a variable of Guid type
Dim assetID As Guid
' Get the value from the query string
getValue("id", assetID)

' Declare a variable of Integer type
Dim imageWidth As Integer

' Get the value from the query string
getValue("imageWidth", imageWidth)

And for the function itself:

''' 
''' Gets the value of the query string key specified
''' 
''' The data type of the value to be returned
''' The query string key''' The variable to store the value in
Public Shared Sub getValue(Of T)(ByVal key As String, ByRef value As T)
    If Not String.IsNullOrEmpty(Request.QueryString.Item(key)) Then
        'If the passed in type is Guid
        If GetType(T) Is GetType(Guid) Then
            ' Check the format of the query string for a valid Guid
            If isValidGuid(Convert.ToString(Request.QueryString.Item(key))) Then
                ' Type cast the value from a string to a Guid                 
                value = DirectCast(CType(New Guid(Convert.ToString(Request.QueryString.Item(key))), Object), T)
            Else
                ' Type cast the an empty guid for the value           
                value = DirectCast(CType(Guid.Empty, Object), T)
            End If
        Else
            ' Type cast query string value to the requested type     
            value = CType(Convert.ChangeType(Request.QueryString.Item(key).Trim(), GetType(T)), T)
        End If
    End If
End Sub
// //]]>