Sorting Displays in Data View Web Parts

I figured out a great little trick for sorting a DVWP-based display based on a column name passed in the Query String.  You can see this in action in the default All Items or All Documents views in lists or libraries.  When you click on the column headers that allow sorting, the browser is sent to the same page with the Query String looking something like:


By passing the column name that you want to sort on in the Query String, the List View Web Part “knows” what to sort the display on and in what order.

If you want to build analogous functionality in a DVWP, you can easily rig the column headers to act the same way, but the trick is to get the items to then sort correctly.  In your body template, you need some XSL like the following:

<xsl:variable name="AscDesc">
  <xsl:when test="string-length($SortDir) = 0 or $SortDir = 'Asc'">ascending</xsl:when>
<xsl:for-each select="$Rows">
 <xsl:sort select="@*[name()=$SortField]" order="{$AscDesc}" />  
 <xsl:call-template name="Community_ContentDetailed.rowview">
  <xsl:with-param name="SiteType" select="$SiteType" /> 
  <xsl:with-param name="CommunityContentFilterValue" select="$CommunityContentFilterValue" /> 

The cool line is #8.  It allows you to take the Query String value for SortField and use it as the column name by which to sort.  The select parameter in the xsl:sort evaluates to @ContentType (from the URL above).

I wanted to be able to easily add the sorting option to header columns in my DVWPs, so I created the following utility template to create the links.  It decides based on the Query String values whether this is the first or second click of the column header (ascending or descending) and shows the appropriate image indicator for the result.

 <xsl:template name="SortHeader">
  <xsl:param name="LinkText"/>
  <xsl:param name="ColumnName"/>
  <xsl:param name="SortField"/>
  <xsl:param name="SortDir"/>
  <xsl:variable name="ASortIMG" select="'/_layouts/images/sortaz.gif'"/>
  <xsl:variable name="DSortIMG" select="'/_layouts/images/sortza.gif'"/>
  <xsl:variable name="SortableIMG" select="'/SiteCollectionImages/sortable.gif'"/>
  <xsl:variable name="AscDesc">
    <xsl:when test="$ColumnName = $SortField and (string-length($SortDir) = 0 or $SortDir = 'Asc')">Desc</xsl:when>
  <img alt="Sortable" border="0" src="{$SortableIMG}"/>
  <a href="#">
   <xsl:attribute name="onclick">
    document.location = '<xsl:value-of select="$URL"/>' +
     '?SortField=' + '<xsl:value-of select="$ColumnName"/>' +
     '&amp;SortDir=' + '<xsl:value-of select="$AscDesc"/>';
   <xsl:value-of select="$LinkText"/>
   <span style="padding-left:2px;">
    <xsl:when test="$ColumnName = $SortField and ($SortDir = '' or $SortDir = 'Asc')">
     <img alt="Ascending - Click to Reverse" border="0" src="{$ASortIMG}"/>
    <xsl:when test="$ColumnName = $SortField and $SortDir = 'Desc'">
     <img alt="Descending - Click to Reverse" border="0" src="{$DSortIMG}"/>