ASP.NET Web Forms Server Control Event Model

An important feature of ASP.NET Web Forms pages is that you can program them 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 Forms page and then write an event handler for the button's click event. Although this is common in Web Forms pages that work exclusively with client script (by handling the button's onclick event in dynamic HTML), ASP.NET Web Forms bring this model to server-based processing.

Note

This topic applies only to ASP.NET Web Forms pages. It does not apply to pages that you create using ASP.NET MVC (Model View Controller) or ASP.NET Web Pages.

Events raised by ASP.NET Web Forms 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 Forms 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 Forms 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 Forms 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 Forms pages that you should be aware of.

Event Set for Server Controls and Pages

Because most ASP.NET Web Forms 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, the CheckBox Web server control raises a CheckedChanged event in server code when the user clicks the box. Some server controls support more abstract events. The Calendar Web server control raises a SelectionChanged 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 ASP.NET Web Forms Server Control Event Model.

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.

Event Arguments

Server-based ASP.NET Web Forms 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 EventArgs, but for some controls is of a type specific to that control. For example, for an ImageButton Web server control, the second argument is of type ImageClickEventArgs, which includes information about the coordinates where the user has clicked.

Note

Events for the page (for example, the page's Load event) can accept the standard two arguments, but no values are passed in these arguments.

Postback and Non-Postback Events in Server Controls

In Web Forms 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 the TextBox control, do not immediately cause a post. Instead, they are raised the next time a post occurs.

Note

If the browser supports it, validation controls can check user input using client script, without a round trip to the server. For details, see Validating User Input in ASP.NET Web Pages.

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 ASP.NET Page Life Cycle Overview.

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's AutoPostBack property to true, as soon as a user clicks the check box, the page is sent to the server for processing.

Note

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 Client Script in ASP.NET Web Pages.

Forwarded Events

In Web Forms pages, Web server controls such as the Repeater, DataList, GridView, FormView, and DetailsView 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.

Note

The GridView, DataList, and other data controls support additional events, such as EditCommand, DeleteCommand, and UpdateCommand, that are special cases of forwarded events.

With server control 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 the ItemCommand event. 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 Events and Delegates.

In ASP.NET Web Forms 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 How to: Create Event Handlers in ASP.NET Web Forms Pages.

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 Click event of an ASP.NET Button server control to a method named ButtonClick.

<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:

Private Sub ButtonClick(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles SampleButton.Click

Binding Web Forms Page Events

ASP.NET Web Forms 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 run 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.

Note

Page event-handling methods do not require any arguments.

If you prefer, you can bind handlers to events explicitly. The automatic binding of page events based on the method naming convention is controlled by a page property named AutoEventWireup. By default, for C#, 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 @ Page directive. You can then create methods with any name and bind them to page events explicitly.

By default, for Visual Basic, this property is set to false. In Visual Basic, handlers are bound to events by using the Handles keyword. This keyword is inserted automatically by Visual Studio as part of the method that you create when you select a page event from the drop-down box. The following example illustrates use of the Handles keyword:

Sub MyPageLoad(sender As Object, e As EventArgs) Handles MyBase.Load

One 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 event handlers. Another disadvantage is that performance is slightly affected, because ASP.NET searches for methods at run time. For a Web site with high traffic volumes, the impact on performance could be a factor in overall site performance.

Note

If you include explicit binding for page events, be sure that the AutoEventWireup property is set to false so that the method is not 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:

Dim b As New Button
b.Text = "Click"
AddHandler b.Click, AddressOf ButtonClick
Placeholder1.Controls.Add(b)
Button b = new Button;
b.Text = "Click";
b.Click += new System.EventHandler(ButtonClick);
Placeholder1.Controls.Add(b);

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 in Web Forms pages. 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, see Client Script in ASP.NET Web Pages and How to: Add Client Script Events to ASP.NET Web Server Controls.

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 Web 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, the BeginRequest event of the HttpApplication 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 EndRequest 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 a Start and an End 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.

    Note

    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, see ASP.NET Application Life Cycle Overview for IIS 5.0 and 6.0 and Global.asax Syntax.

See Also

Tasks

How to: Create Event Handlers in ASP.NET Web Forms Pages

Concepts

ASP.NET State Management Overview

Other Resources

Server Event Handling in ASP.NET Web Forms Pages

Server Event Handling in ASP.NET Web Forms Pages