Web 2.0 ASP.NET

A Blog about ASP.NET, MVC, Web 2.0, AJAX, SQL server and other web technologies.
Helping the little guy win!

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

Introduction
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
aspx


<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
{
[WebMethod]
public static void HandleImageLoad()
{
// handling here
}
}

0 comments:

Visual Studio 2008

Microsoft Store

Microsoft Store

About Me

My Photo
David Ridgway
MCSD MCAD MCSE David has been architecting and developing software applications for the last 10 years using Microsoft technologies, more recently he has specialized in developing Web 2.0 ASP.NET applications using C#, SQL Server, AJAX, JavaScript and other development tools. When not tapping on the keyboard programming you can find him strumming guitars, banging drums and tinkling the piano keys in local bars and cafes around Osaka.
View my complete profile

Syntax

Syntax Highlighter

Expression Studio 3

Now Reading







Disclaimer

All data and information provided in THIS blog is for informational purposes only. I make no representations as to accuracy, completeness, currentness, suitability, or validity of any information on this blog and will not be liable for any errors, omissions, or delays in this information or any losses, injuries, or damages arising from its display or use. All information is provided on an as-is basis. All code may be used under the standard UIIYW BDBMIITDW license (Use It If You Want But Dont Blame Me If It Doesnt Work) :)