Document directory
- Bind control event
- Binding page events
- Explicit binding of dynamic controls
ASP. NET has an important feature that allows you to program web pages through event-based models similar to those in client applications. For example, you can add a button to an ASP. NET webpage and write an event handler for the Click Event of the button. In this case, only client scripts are used (the buttons are processed in Dynamic HTML ).OnclickEvent), but ASP. NET introduces this model to server-based processing.
Compared with events in traditional HTML pages or client-based Web applications, events triggered by ASP. NET Server controls work in a slightly different way. The main cause of the difference is the separation between the event itself and the location where the event is handled. In client-based applications, events are triggered and processed on the client. However, in ASP. NET Web pages, events associated with server controls are triggered on the client (browser), but ASP. NET pages are processed on the Web server.
For events triggered on the client, the ASP. NET Web control event model requires that the event information be captured on the client and the event message be transmitted to the server through http post. The page must interpret the POST to determine the event that occurred, and then call the corresponding method in the code on the server to process the event.
ASP. NET processes tasks such as capturing, transmitting, and interpreting events. When you create an event handler on an ASP. NET web page, you generally do not need to consider capturing event information and making it available to your code. You can create an event handler in the same way as you create an event handler on a traditional Client form. Even so, event processing in ASP. NET web pages still has something you should pay attention.
Server controls and page event groups
Most ASP. NET Server control events require that the round-trip to the server be processed, so these events may affect the page performance. Therefore, the server control only provides a limited set of events, usually limited to Click events. Some server controls support the Change event. For example, the CheckBox Web Server Control triggers the CheckedChanged event in the server code when you click this box. Some server controls support more abstract events. For example, the Calendar Web Server Control triggers the SelectionChanged event, which is a more abstract version of the Click event.
For server controls, events that occur frequently (and are triggered when the user does not know) are not supported, suchOnmouseoverEvent. ASP. NET Server controls can still call client handlers for these events. The ASP. NET Web server control event model in the following section will describe this.
The control and page itself will also trigger lifecycle events in each processing step, suchInit,LoadAndPreRender. You can use these lifecycle events in your application. For exampleLoadEvent, you can set the default value of the control.
Event Parameters
Server-based ASP. NET page and control events follow the standard. NET Framework mode of the event handler method. Two parameters are passed for all events: the object that triggers the event and the event object that contains any event-specific information. The second parameter is usually of the EventArgs type, but is specific to some controls. For example, for the ImageButton Web Server Control, the second parameter is of the ImageClickEventArgs type, which contains information about the coordinates of the user's clicked position.
Note: |
Page events (for example, Load events on this page) can accept two standard parameters, but do not pass values through these parameters. |
Sending and unsending events in the Server Control
In server controls, some events (usually Click events) cause the page to be immediately sent back to the server. The Change event in HTML server controls and Web server controls (such as TextBox controls) does not immediately cause the page to be sent. They are triggered in the next sending operation.
Note: |
If the browser supports this function, the verification control can use a client script to check user input without the need for a round trip to the server. For more information, see verifying user input on the ASP. NET webpage. |
After a page is sent back, the page initialization event (Page_InitAndPage_Load), And then process the control event. If you do not have a thorough understanding of page event processing, do not create application logic that relies on Change events triggered in a specific order. For more information, see ASP. NET page lifecycle overview.
If it is useful for your application, you can specify it so that the Change event can cause the page to be sent. Web server controls that support Change events includeAutoPostBackAttribute. When this attribute isTrueControl changes will cause the page to be sent immediately without waiting for the Click event. For example, by default,CheckBoxControlCheckedChangedThe event does not cause the page to be submitted. However, if you set the AutoPostBack attribute of the controlTrueThe page is immediately sent to the server for processing once you click the check box.
Note: |
ForAutoPostBackThe property works normally. the user's browser must be set to allow scripts to run. This is the default setting in most cases. However, some users disable running scripts for security reasons. For more information, see the client script in the ASP. NET webpage. |
Forwarded event
Web server controls such as Repeater, DataList, GridView, FormView, and DetailsView can contain button controls that trigger events. For example,GridViewEach row in the control can contain one or more buttons dynamically created by the template.
Unlike events triggered by each button, events from nested controls are forwarded to container controls. Then, the container enables you to discover the parameters of the independent control that triggers the original event, which in turn triggers a general eventItemCommand. By responding to this single event, you can avoid unnecessary writing a separate event handler for the Child control.
ItemCommandAn event includes two standard event parameters: an object that references the event source and an event object that contains event-specific information.
Note: |
GridView,DataListAnd other data controls support other events that are used as special events for event forwarding, for example,EditCommand,DeleteCommandAndUpdateCommand. |
For buttons, you can useCommandArgumentProperty to pass a user-specified string to the event handler to help you determine the button for triggering the event. For exampleDataListIn the control, the button triggers the ItemCommand event. You can setCommandArgumentProperty is set to a different value-A button value may be "ShowDetails", and another button value is "AddToShoppingCart"-these values are subsequently captured in the event handler.
Bind events to methods
An event is a message, for example, "a button has been clicked ". In an application, the message must be converted into a method call in the code. Event messages are bound to specific methods (that is, event handlers) through event delegation. For more information, see events and delegation.
In ASP. NET web pages, if the control is created in the page in the form of declaration (TAG), you do not need to explicitly encode the delegate. Event binding can be completed in various ways, depending on the event to be bound and the programming language used. For more information, see How to create an event handler on the ASP. NET webpage.
Bind control event
For controls declared on the page, you can bind events to methods by setting attributes/properties in the control tag. The following code example demonstrates how to bind the Click Event of the ASP. NET Button control toButtonClick.
Copy
<asp:button id="SampleButton" runat="server"
text="Submit" onclick="ButtonClick" />
If the page has been compiled, ASP. NET searchesButtonClickAnd confirm that the method has an appropriate signature. This method accepts two parameters. One isObjectType, the other isEventArgsType. Then ASP. NET can automatically bind events to methods.
In Visual Basic, you can choose to bind an event to a method using the Handles keyword in the event handler declaration, as shown in the following code example:
VBC # C ++ F # JScript Replication
Private Sub ButtonClick(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles SampleButton.Click
Binding page events
ASP. NET page will causeInit,Load,PreRenderAnd other lifecycle events. By defaultPage _Event nameTo bind page events to methods. For exampleLoadEvent creation handler, which can be created with the namePage_Load. During compilation, ASP. NET searches for methods based on this naming convention and automatically executes the binding between events and methods. You canPageUse of any events exposed by classPage _Event name.
Note: |
Page event processing method does not require any parameters. |
If you want to, you can create a handler explicitly. Automatic Binding of page events based on method naming conventionsAutoEventWireupPage property control. By default, this attribute is setTrueAnd ASP. NET will perform the automatic search and binding described above. You can also set this PropertyFalseIn the @ Page command, addAutoEventWireup = falseAttribute ). You can then create methods with any name and explicitly bind these methods to page events. In Visual Basic, you can use the Handles keyword, as shown in the following code example:
VBC # C ++ F # JScript Replication
Sub MyPageLoad(sender As Object, e As EventArgs) Handles MyBase.Load
AutoEventWireupThe disadvantage of an attribute is that it requires the page event handler to have a specific and predictable name. This limits the flexibility in naming event handlers.
Note: |
If explicit binding of page events is included, make sure thatAutoEventWireupSet propertyFalseSo that the method is not accidentally called twice. |
Explicit binding of dynamic controls
If you create a control by using the tag declaration control, you can use the property (suchOnclick) Bind the event to the method. In Visual Basic, the Handles keyword should be used. If you want to dynamically create controls (using code), you cannot use any of the above methods, because the compiler does not reference the controls during compilation.
In this case, explicit event binding is required. In Visual Basic, you can use the AddHandler statement to bind events in dynamically created controls to existing methods. In C #, you can create a delegate and associate it with the control event. The following code example shows howButtonClickMethod bound to the buttonClickEvent:
VBC # C ++ F # JScript Replication
Dim b As New Button
b.Text = "Click"
AddHandler b.Click, AddressOf ButtonClick
Placeholder1.Controls.Add(b)
Responds to client and server events in ASP. NET Server controls
This topic discusses how to handle events triggered in server code. Controls display elements in the browser, and these elements can also cause client events. You can use the client script to process these events. Using client scripts, you can add mouse and keyboard events to the ASP. NET Server Control. For more information, see the client script in the ASP. NET webpage and how to add client script events to the ASP. NET Web server control.
Applications and session events
ASP. NET also provides you with multiple methods to process lifecycle events, which can be triggered when the application starts or stops, or when a single user's session starts or stops, including:
All requests to the application will trigger application events. For example, when you request any ASP. NET webpage or XML Web services in an application, an HttpApplication object (Application_BeginRequest)BeginRequest event. This event allows you to initialize resources that are used for each request to the application. Corresponding event, that isHttpApplicationObject EndRequest event (Application_EndRequest), So that you can close or release the resources used for this request.
Session events are similar to application events (session events include Start and End events), but session events are triggered by each unique session in the application. When you start a session from the application request page for the first time, when the application explicitly closes the session or when the session times out, the session ends.
Note: |
Session_EndEvents are not triggered under any circumstances. For more information, seeEnd. |
You can create a handler for these types of events in the Global. asax file. For more information, see ASP. NET application lifecycle overview and Global. asax syntax.
See task
What is: Create an event handler on an ASP. NET webpage