ASP.NET Event Model

One of the key features of ASP.NET is that it uses an event-based programming model. In the simple Hello World example covered in chapter one, we added a small bit of programming to a method named Page_Load. This method is in fact an event handler. An event handler is a method that determines what actions are performed when an event occurs, such as when the user clicks a button or selects an item from a list. When an event is raised, the handler for that specific event is executed. Events can in fact be assigned to multiple handlers. As well, methods that handle particular events can be set or changed dynamically.

In the .NET Framework, all event handlers have a specific method signature, that is, a specific return type and parameters. Event handlers are always void methods (or Sub methods in Visual Basic). Event handlers always accept two parameters: an object parameter and an EventArgs parameter (or a subclass of EventArgs, such as CommandEventArgs or ImageClickEventArgs). The object parameter references the object that raised the event. If you used the same event handler method for multiple controls, the object parameter can be used to determine which control triggered the event. The EventArgs parameter (or its subclass) contains information specific to the particular event.  For instance, the ImageClickEventArgs parameter contains the x and y coordinates of where the user clicked in the image.

It is important to note that the event system in ASP.NET operates in a different manner than in a Windows application or from the event system in browser-based Javascript. In a Windows application, for instance, events are raised and handled on the same processor. In contrast, ASP.NET events are raised on the client (the browser) but transmitted to and handled on the server (as shown below).

Client-based event system versus ASP.NET event system

Since its event handling requires a round-trip to the server, ASP.NET offers a smaller set of events in comparison to a totally client-based event system. Events that occur very frequently, such as mouse movement or drag-and-drop events, are not really supported by ASP.NET (though it is still possible to use client-side event handlers for these types of events in Javascript), or to use an AJAX-based API such as ASP.NET AJAX or AJAX.NET).