|Important||This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer|
ASP.NET Web Server Control Event Model
An important feature of ASP.NET is that it allows you to program Web pages using an event-based model that is similar to that in client applications. As a simple example, you can add a button to an ASP.NET Web page and then write an event handler for the button's click event. Although this is common in Web pages that work exclusively with client script (by handling the button's onclick event in dynamic HTML), ASP.NET brings this model to server-based processing.
Events raised by ASP.NET server controls work somewhat differently than events in traditional HTML pages or in client-based Web applications. The difference arises primarily because of the separation of the event itself from where the event is handled. In client-based applications, events are raised and handled on the client. In ASP.NET Web pages, however, events associated with server controls originate on the client (browser) but are handled on the Web server by the ASP.NET page.
For events raised on the client, the ASP.NET Web control event model requires that the event information be captured on the client and an event message transmitted to the server, through an HTTP post. The page must interpret the post to determine what event occurred and then call the appropriate method in your code on the server to handle the event.
ASP.NET handles the task of capturing, transmitting, and interpreting the event. When you create event handlers in an ASP.NET Web page, you can typically do so without thinking about how the event information is captured and made available to your code. Instead, you can create event handlers in much the same way you would in a traditional client form. However, there are some aspects of event handling in ASP.NET Web pages that you should be aware of.
Event Set for Server Controls and Pages
Because most ASP.NET server control events require a round trip to the server for processing, they can affect the performance of a page. Therefore, server controls offer a limited set of events, usually only click-type events. Some server controls support change events. For example, theWeb server control raises a event in server code when the user clicks the box. Some server controls support more abstract events. For example, the Web server control raises a event that is a more abstract version of a click event.
Events that occur often (and can be raised without the user knowing it), such as an onmouseover event, are not supported for server controls. ASP.NET server controls can still call client-side handlers for those events, as explained later under.
Controls and the page itself also raise life-cycle events at each processing step, such as Init, Load, and PreRender. You can take advantage of these life-cycle events in your application. For example, in a page's Load event, you can set default values for controls.
Server-based ASP.NET page and control events follow a standard .NET Framework pattern for event-handler methods. All events pass two arguments: an object representing the object that raised the event, and an event object containing any event-specific information. The second argument is usually of type, but for some controls is of a type specific to that control. For example, for an Web server control, the second argument is of type , which includes information about the coordinates where the user has clicked.
Events for the page (for example, the page'sevent) can accept the standard two arguments, but no values are passed in these arguments.
Postback and Non-Postback Events in Server Controls
In server controls, certain events, typically click events, cause the page to be posted back immediately to the server. Change events in HTML server controls and Web server controls, such as thecontrol, do not immediately cause a post. Instead, they are raised the next time a post occurs.
If the browser supports it, validation controls can check user input using client script, without a round trip to the server. For details, see.
After a page has been posted back, the page's initialization events (Page_Init and Page_Load) are raised, and then control events are processed. You should not create application logic that relies on the change events being raised in a specific order unless you have detailed knowledge of page event processing. For details, see.
If it useful for your application, you can specify that change events cause the page to post. Web server controls that support a change event include an AutoPostBack property. When this property is true, the control's change event causes the page to post immediately, without waiting for a click event. For example, by default, a CheckBox control's CheckedChanged event does not cause the page to be submitted. However, if you set the control'sproperty to true, as soon as a user clicks the check box, the page is sent to the server for processing.
For the AutoPostBack property to work properly, the user's browser must be set to allow scripting. This is the default in most cases. However, some users disable scripting for security reasons. For details, see.
Web server controls such as the, , , , and controls can contain button controls that themselves raise events. For example, each row in a GridView control can contain one or more buttons created dynamically by templates.
Rather than each button raising an event individually, events from the nested controls are forwarded to the container control. The container in turn raises a generic ItemCommand event with parameters that allow you to discover which individual control raised the original event. By responding to this single event, you can avoid having to write individual event handlers for child controls.
The ItemCommand event includes the two standard event arguments, an object referencing the source of the event and an event object containing event-specific information.
The GridView, DataList, and other data controls support additional events, such as EditCommand, DeleteCommand, and UpdateCommand, that are special cases of forwarded events.
With buttons, you can use the CommandArgument property to pass a user-specified string to the event handler to help you identify what button raised the event. For example, in a DataList control, buttons raise theevent. You can set the CommandArgument property of each button to a different value—perhaps one button's value is "ShowDetails" and another button's value is "AddToShoppingCart"—and then capture those values in the event handler later.
Binding Events to Methods
An event is a message like "a button has been clicked". In your application, the message must be translated into a method call in your code. The binding between the event message and a specific method—that is, an event handler—is done using an event delegate. For more information, see.
In ASP.NET Web pages, you do not need to explicitly code delegates if the control is created declaratively (in markup) on the page. Event binding can be accomplished in various ways, depending on what event you are binding and what programming language you are using. For details, see.
Binding Control Events
For controls declared on the page, you can bind an event to a method by setting an attribute (property) in the control's markup. The following code example shows how to bind the
<asp:button id="SampleButton" runat="server" text="Submit" onclick="ButtonClick" />
When the page is compiled, ASP.NET looks for a method named
ButtonClick and confirms that the method has the appropriate signature (it accepts two arguments, one of type Object and another of type EventArgs). ASP.NET then automatically binds the event to the method.
In Visual Basic, you can alternatively bind events to methods using the Handles keyword in the event handler declaration, as in the following code example:
Binding Page Events
ASP.NET pages raise life-cycle events such as Init, Load, PreRender, and others. By default, you can bind page events to methods using a naming convention of Page_eventname. For example, to create a handler for the page's Load event, you can create a method named Page_Load. At compilation time, ASP.NET will find methods based on this naming convention and automatically perform the binding between the event and the method. You can use the convention of Page_eventname for any event exposed by the Page class.
Page event-handling methods do not require any arguments.
If you prefer, you can create handlers explicitly. The automatic binding of page events based on the method naming convention is controlled by a page property named AutoEventWireup. By default, this property is set to true, and ASP.NET performs the automatic lookup and binding described earlier. Alternatively, you can set this property to false by adding the attribute
AutoEventWireup=false in the directive. You can then create methods with any name and bind them to page events explicitly. In Visual Basic, you can use the Handles keyword, as in the following code example:
The disadvantage of the AutoEventWireup attribute is that it requires that the page event handlers have specific, predictable names. This limits your flexibility in how you name your event handlers.
If you include explicit binding for page events, be sure that the AutoEventWireup property is set to false so that the method is not inadvertently called twice.
Explicit Binding for Dynamic Controls
If you create controls by declaring them in markup, you can bind events to methods using an attribute (for example, onclick) or in Visual Basic, by using the Handles keyword. If you create controls dynamically (in code), you cannot use either of these methods, because the compiler does not have a reference to the control at compilation time.
In that case, you must use explicit event binding. In Visual Basic, you can use the AddHandler statement to bind an event in a dynamically created control to an existing method. In C#, you create a delegate and associate it with the control's event. The following code example shows how you can bind a method named
ButtonClick to a button's Click event:
Responding to Both Client and Server Events in ASP.NET Server Controls
This topic has discussed how to work with events raised in server code. Controls render elements to the browser, and those elements can also raise client-side events that you can handle in client script. Using client script, you can add mouse and keyboard event handling to ASP.NET server controls. For more information, seeand .
Application and Session Events
In addition to page and control events, ASP.NET provides ways for you to work with life-cycle events that are raised when your application starts or stops or when an individual user's session starts or stops, including the following:
Application events are raised for all requests to an application. For example, theevent of the object (Application_BeginRequest) is raised when any ASP.NET Web page or XML Web service in your application is requested. This event allows you to initialize resources that will be used for each request to the application. A corresponding event, the event of the HttpApplication object (Application_EndRequest), provides you with an opportunity to close or otherwise dispose of resources used for the request.
Session events are similar to application events (there is aand an event), but are raised with each unique session within the application. A session begins when a user requests a page for the first time from your application and ends either when your application explicitly closes the session or when the session times out.
The Session_End event is not raised under all circumstances. For details, see End.
You can create handlers for these types of events in the Global.asax file. For details, seeand .