Encoding Query String Values Between .ASPX Pages

I ran into an instance today where a column’s data contained the ampersand (&) character when I hadn’t expected it to.  Since the ampersand is used to separate Query String name/value pairs in the URL, that ampersand was causing me problems.

In general, you should always encode Query String values just in case they might contain a reserved character.  Here’s the code snippet from my page (In another section of my XSL, I pass the selected value on the Query String.):

            <xsl:if test=”@Business_x0020_Group = $Group”>
                <xsl:attribute name=”selected”>true</xsl:attribute>
            <xsl:attribute name=”value”>
                <xsl:value-of select=”ddwrt:UrlEncode(string(@Business_x0020_Group))” />
            <xsl:value-of select=”@Business_x0020_Group” />

As you can see in the bolded line, the ddwrt:UrlEncode function takes care of things for me.  Note that you must do the explicit type conversion to string or you will get an error.  (This is the case with most of the ddwrt namespace functions.)  In the case where I had a Business Group with the string ‘[RR&C]’ in it, the ddwrt:UrlEncode function returned ‘%5bRR%26C%5d’, which can be passed as a Query String value with no issues.