Export (0) Print
Expand All
43 out of 58 rated this helpful - Rate this topic

ASP.NET Server Control Event Model

Visual Studio .NET 2003

Events raised by ASP.NET server controls work somewhat differently than events in traditional client forms 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 Web Forms pages, on the other hand, events associated with server controls are raised on the client but handled on the Web server by the ASP.NET page framework.

For events raised on the client, the Web Forms control event model requires that the event information be captured on the client and an event message transmitted to the server, via an HTTP post. The page framework 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. For more information, see Events in ASP.NET Server Controls.

The Web Forms control event model

59t350k3.vbwebformseventmodel(en-us,VS.71).gif

ASP.NET handles virtually all the mechanics of capturing, transmitting, and interpreting the event. When you create event handlers in a Web Forms page, you can do so without thinking about the mechanics of 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 do so in a traditional client form. Even so, there are some aspects of event handling in Web Forms pages that you should be aware of.

Intrinsic Event Set

Because most Web Forms events require a round trip to the server for processing, they can affect the performance of a form. Therefore, server controls offer a limited set of intrinsic events, usually only click-type events. Some server controls support a special version of the onchange event, which is raised when the control's value changes. For example, the CheckBox Web server control raises a change event when the user clicks the box. Events that occur often (and can be raised without the user knowing it), such as an onmouseover event, are not supported for server controls.

Note   Some server controls support a set of higher-level events. For example, the Calendar Web server control raises a SelectionChanged event that is a more abstract version of a Click event.

Event Arguments

Web and HTML server 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 System.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 the type ImageClickEventArgs, which includes information about the coordinates where the user has clicked.

Postback and Non-Postback Events in Web Server Controls

In Web server controls, certain events, typically click events, cause the form to be posted back to the server. Change events in HTML server controls and Web server controls, such as the TextBox control, are captured but do not immediately cause a post. Instead, they are cached by the control until the next time a post occurs. Then, when the page is processed on the server again, all the pending events are raised and processed.

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 Introduction to Validating User Input in Web Forms.

During server page processing, events are processed first, in no particular order. When all change events have been processed, the click event that caused the form to be posted is processed.

Note   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 more information, see Postback Event Sample.

You can specify that a change event cause a form 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 form 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, by setting the control's AutoPostBack property to true, you specify that 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 ASP.NET Server Controls and Browser Capabilities.

Bubbled Events

Web server controls such as the Repeater, DataList, and DataGrid controls can contain button controls that themselves raise events. For example, each row in a DataGrid 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 bubbled — that is, they're sent to the container. The container in turn raises a generic event called ItemCommand 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 DataGrid and DataList Web server controls support additional events, such as EditCommand, DeleteCommand, and UpdateCommand, which are special cases of bubbled 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 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.

Event Delegates in Web Forms Pages

An event is a message — effectively, something like "a button has been clicked". In your application, you want the message to be translated into a method call in your code, such as "Button1_Click". 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 Web Forms pages, you typically do not need to explicitly code delegates. If you use the Web Forms Designer in Visual Studio, the designer generates code that automatically binds events to methods. In Visual Basic, this is done using the Handles keyword in the event handler declaration, as in this example:

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

In Visual C#, the designer generates an explicit event-handler delegate in the page, similar to the following:

private void InitializeComponent()
{   
   this.Load += new System.EventHandler(this.Page_Load);
}

Alternatively, the ASP.NET page framework also supports an automatic way to associate page events and methods. If the AutoEventWireup attribute of the Page directive is set to true (or if it is missing, since by default it is true), the page framework calls page events automatically, specifically the Page_Init and Page_Load methods. In that case, no explicit Handles clause or delegate is needed.

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. Therefore, in Visual Studio, the AutoEventWireup attribute is set to false by default and the designer generates explicit code to bind page events to methods.

If you do set AutoEventWireup to true, Visual Studio will generate code to bind the events and the page framework will automatically call events based on their names. This can result in the same event code being called twice when the page runs. As a consequence, you should always leave AutoEventWireup set to false when working in Visual Studio.

Responding to Both Client and Server Events in ASP.NET Server Controls

For the most part, you will be primarily interested in events that are raised in server code. However, if it is appropriate for your application, you can also handle client-side events for ASP.NET server controls by writing client script.

Note   You cannot use HTML syntax to bind to client-side events for Web server controls. Instead, you have to add event-binding attributes in code. For an example, see the table below.

For example, you might have an HTML image button element that you have converted to an HTML server control. Typically, in a Web Forms page you would handle the image button's click event in server code. However, you might also want to use client code to change the image when the user moves the mouse over it. You can do that by creating a client script for the image button's onmouseover event. (In this example, the assumption is that you are working with a browser that supports HTML 4.0, such as Microsoft Internet Explorer 4.0 or later.)

Note   In the case that both the client-side event handler and a server-side event handler have the same event-handler name, the client-side event handler always runs first, then the server event handler. However, it is confusing to allow this scenario, so some planning for a naming convention is strongly suggested.

Handling a Click Event in Client and Server Code

There is one event — the client onclick event — that introduces a difficulty if you want to handle it on both the client and the server. The problem arises because all button server controls (and other controls whose AutoPostBack property is set to true) submit the page to the server. However, in HTML, only a few controls inherently submit a form:

  • The HTML submit button (<INPUT type=submit>), which is the HtmlInputButton control with its type set to Submit or Image. You can add this control from the HTML tab of the Toolbox.
  • The Button Web server control (<asp:button>).

For all other controls that are specified to submit the page, a small client script is written into the page and called to submit the form when the control is clicked. Those controls therefore already use the client-side OnClick event to invoke this submit script.

You can create client-side OnClick handlers for all controls, but you need to choose the approach that works with each type of control. The following table summarizes the strategies you use for different types of controls.

ControlStrategy
HtmlInputButton, which includes HTML server control buttons whose type is set to Submit, Reset, or ImageInclude an onclick attribute in the HTML syntax for the control:
<INPUT Type="Submit" Runat="Server" Value="caption" onclick="clientfunction()"  ...>

On the server side, these types of buttons raise a ServerClick event instead of a simple Click event. The client event is raised first, and then the form is submitted and the server event is handled.

All other HTML controls (those that do not submit a form by default)Include an onclick attribute in the HTML syntax for the control, but follow it with a semicolon (;):
<INPUT Type="Button" Runat="Server" Value="caption" onclick="clientfunction();"  ...>

This causes your function to be called first, before the client-side submit script is called.

Web server controls, including buttons (<asp:button>) and other controls (for example, <asp:checkbox>)You cannot specify a client-side event in the HTML syntax for a Web server control. Instead, add an event attribute to the control at run time in server code using code such as the following:
Button1.Attributes.Add("onclick", "clientfunction();")
Note   For the Button Web server control, you do not need the semicolon, because that control automatically submits the page.

Application and Session Events

In addition to page and control events, the ASP.NET page framework provides ways for you to work with events that can be raised when your application starts or stops or when an individual user's session starts or stops:

  • Application events are raised for all requests to an application. For example, Application_BeginRequest is raised when any Web Forms 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, 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 Session_Start and a Session_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.

You can create handlers for these types of events in the Global.asax file. For details, see Global.asax File and Global.asax Syntax.

See Also

Server Event Handling in Web Forms Pages | Global.asax File | Introduction to Web Forms State Management | Working with Httpapplication Instances

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.