Google Analytics Click Event Tracking on LinkButton in ASP.NET (VB)

Google Analytics integration with .NET web parts requires more planning and execution than with straight HTML. To apply dynamic event tracking to a LinkButton we can attach a function to the OnClientClick attribute of the LinkButton.

First, a review of how the event tracking method is set up directly from Google:

_gaq.push(['_trackEvent', 'category', 'action', 'optional_label', 'optional_value']);

category (required)

The name you supply for the group of objects you want to track.

action (required)

A string that is uniquely paired with each category, and commonly used to define the type of user interaction for the web object.

label (optional)

An optional string to provide additional dimensions to the event data.

value (optional)

An integer that you can use to provide numerical data about the user event.

To set it up on the LinkButton:

<asp:LinkButton ID="lb_mylinkbutton" 
OnClientClick='<%# GetGoogleAnalyticsEventTracking("Downloads", "PDF", "/link/to/myPDF.pdf") %>' 
runat="server">My Link Button</asp:LinkButton>                  

In the code above the values are hard coded, but you can use variables in their place for dynamic links:

<asp:LinkButton ID="lb_mylinkbutton" 
OnClientClick='<%# GetGoogleAnalyticsEventTracking(Eval("link_category"), Eval("link_action"), Eval("link_label")) %>'  
runat="server">My Link Button</asp:LinkButton>    

And, the .NET function, VB flavor:

Protected Function GetGoogleAnalyticsEventTracking(ByVal link_category As String, ByVal link_action As String, ByVal link_label As String) As String

        Return String.Format("_gaq.push(['_trackEvent','{0}','{1}','{2}']);", link_category, link_action, link_label)

End Function

When the user clicks the LinkButton, the Google Analytics track event method will fire and, provided Google Analytics tracking is set up properly on the site, you will see the click events tracked within a day.

Posted in .net, Google Analytics. Tags: , . Permalink. Both comments and trackbacks are closed.

2 Comments

  1. September 27, 2011 at 11:51 am | Permalink

    @Brian
    Yes, it does. That is how I use it in production. The master page loads the GA tracking in the .

    All is working fine. Check where and how the GA is loaded by the master page.

  2. Brian
    September 26, 2011 at 3:55 pm | Permalink

    Does this work with master pages? I have my analytics code on a master page and the button and “GetGoogleAnalyticsTracking” function in the child page, but it doesn’t seem to be recording the event in Analytics. If I move the function to the master page, the page throws an error saying that it can’t find the function. Any ideas?