Tracking visitors in ASP.NET by using an image and AJAX PageMethods

I often see developers asking for ways to track page usage so I thought I’d share a trick I often use, it’s very simple, doesn’t require Http Handlers and takes just a couple of minutes to implement.

The Method
Ok, so let’s get to it as it will take you less time to implement than it takes me to tell you! Every image has an onload event associated with it, so using this event we are going to call a page method in our code behind file *blink* yes that simple! Slapping yourself already, yes I did too when it came to me.

1. Add a script manager to your page or master page (tut tut if don’t have one already, this is the AJAX revolution!) Make sure you set the EnablePageMethods property to true). Also make sure the script manager is inside your form tag.
2. Create a public static method in your code behind with [WebMethod] above it and add System.Web.Webservices to your usings. Add your handling code, you could update your database, increment a counter or write to a log file.
3. Add an image to your page which has an onload=”PageMethods.TheNameOfYourPageMethod” attribute.

You’re done! Pat yourself on your back and grab a latte

The Code

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"/>
<img src="clear.png" onload="PageMethods.HandleImageLoad()" />

Code behind

using System.Web.Services;

public partial class _Default : System.Web.UI.Page
public static void HandleImageLoad()
// handling here