Google Analytics cross domain tracking with server side redirect in ASP.Net Webforms

Google Analytics cross domain tracking allows tracking of multiple domains (or sub-domains) in a single Analtics profile.  There are loads of great resources for how to implement this, including in unusual client side navigation.

I have come across an issue when using ASP.Net Webforms, where there is a single form for the page and multiple submit actions (server side button onclicks etc) and when we also need a simple form to submit to a different domain.  It then becomes more complex to call the relevant client side Google Analytics methods.

This re-affirms one of the major drawbacks of ASP.Net Webforms and ASP.Net MVC as a much better option. However, that is not always available for existing projects 🙂

[UPDATED POST: Previous method attempted to get GA cookie values on the server side. This is not as straightforward as I previously thought.]

The possible solutions include:

Option 1: Changing the form’s “action” attribute on the client (using javascript) when the relevant button is clicked.  This is a pretty fragile solution.  Problems include unnecessary form fields passed to the external domain and issues where the form action must be returned to the original.

Option 2: It may also be possible to have a second form placed outside the “server” form on the page and either position it using CSS or set values and submit with client side code. Again, this adds extra client side complexity.

Option 3: Another option is to do the redirect on the client.  This may involve getting values of multiple form controls in javascript and building a URL, then using the Google Analytics “_link” method.  Issues with this solution include possible client code complexity and no graceful fallback for non-javascript situations. It may also not be an option is server side  functionality is required before the redirect.

Option 4: The previous solution I covered in this post was inspired by this Stack Overflow answer. However, I found further complications which make this a less attractive solution.

Option 5: My solution in this specific situation is to pass the full redirect URL to the server via a hidden form field.  A client side event calls the Google Analytics API to append the relevant querystring before the form is submitted.  This means that the server side redirect will have the correct URL including all the __utm* variables.

Here is the code:

I would be interested to hear about any improvements or better options!