2.3 Events


Many of the server-side controls in ASP.NET can generate server-side events in addition to simply acting as state retainers. The server-side control that most obviously generates server-side events is the button. When a client clicks a button in a form, the form is typically submitted back to the server via a POST request, as we have seen in earlier examples in this chapter. What we have not explored yet is the ability to link server-side functions in our Page -derived class.

Server-side events are implemented using the standard event mechanism in the CLR: delegates. Controls that generate server-side events typically expose events of the generic EventHandler delegate type. [5] To register a handler for a server-side event, you must first define a method in your Page -derived class whose signature matches that of the EventHandler delegate. Then you must create a new instance of the EventHandler delegate initialized with your handler and subscribe it to the event exposed by the control. Listing 2-5 shows a sample page that registers an event handler for the ServerClick event of the HtmlInputButton server-side control.

[5] Some controls define their own event handler delegates to pass additional information. For example, items within a datagrid expose events using the DataGridItemEventHandler , which takes a reference to a DataGridItemEventArgs class containing a link to the item for which the event was fired .

Listing 2-5 Server-Side Event Handler Using Explicit Delegate Subscription
 <!-- event.aspx --> <%@ Page Language="VB" %> <html> <script runat=server> Protected Sub OnClickMyButton(src As Object, _                               e As EventArgs)   _message.InnerText = "You clicked the button!" End Sub Protected Sub Page_Init(src As Object, e As EventArgs)   AddHandler _MyButton.ServerClick, _              New EventHandler(AddressOf OnClickMyButton) End Sub </script> <body>   <form runat=server>     <h2>ASP.NET event page</h2>     <p>     <input type=button id=_MyButton            value="Click me!" runat=server />     </p>     <span id=_message runat=server/>   </form> </body> </html> 

Note that in our implementation we provided a handler for the Init event of our Page -derived class using the AutoEventWireup described in Chapter 1 (by simply naming the function Page_Init ). Within this handler, we explicitly created a new EventHandler delegate instance, initialized with the OnClickMyButton function, and subscribed that delegate to the ServerClick event of the HtmlInputButton control on our page. When the button is now clicked in the client browser, our event handler is invoked during the post-back sequence.

An alternative syntax for wiring up event handlers to server-side controls is to add an attribute to the control's tag in the page named OnEvent , where Event is the name of the event you would like to subscribe to. The value for this attribute should be the name of the server-side method in your Page -derived class you would like to have called when the event is fired. For example, instead of explicitly wiring up the delegate as we did in Listing 2-5, we could annotate the input control tag as shown in Listing 2-6.

Listing 2-6 Server-Side Event Handler Using OnEvent Syntax
 <!-- event.aspx --> <%@ Page Language="VB" %> <html> <script runat=server> Protected Sub OnClickMyButton(src As Object, _                               e As EventArgs)   _message.InnerText = "You clicked the button!" End Sub </script> <body>   <form runat=server>     <h2>ASP.NET event page</h2>     <p>     <input type=button id=_MyButton            value="Click me!"            OnServerClick="OnClickMyButton" runat=server />     </p>     <span id=_message runat=server/>   </form> </body> </html> 

It is important to understand that server-side events are generated as part of the post-back sequence and are issued through the standard HTTP POST mechanism. Because a given page always issues a generic POST request to the server, it is not obvious how to map a particular post-back request onto server-side events. For example, if we have multiple buttons on a page, each of which has a designated server-side handler, how does ASP.NET know which event to fire when a POST occurs to the page? Listing 2-7 shows a sample page with this problem. There are three separate buttons, and each button has a distinct handler whose implementation changes the color of the server-side div element. If some additional information is not sent through the POST issued by each of these buttons, it will be impossible for ASP.NET to tell which button was pressed and to invoke only the handler for that particular button.

Listing 2-7 Color Page Demonstrating Three Separate Server-Side Event Handlers
 <!-- color.aspx --> <%@ Page Language="VB" %> <html> <script runat=server> Protected Sub OnRed(src As Object, e As EventArgs)   _color.Style("background-color") = "Red" End Sub Protected Sub OnGreen(src As Object, e As EventArgs)   _color.Style("background-color") = "Green" End Sub Protected Sub OnBlue(src As Object, e As EventArgs)   _color.Style("background-color") = "Blue" End Sub Protected Sub Page_Init(src As Object, e As EventArgs)   AddHandler _redButton.ServerClick, _              New EventHandler(AddressOf OnRed)   AddHandler _greenButton.ServerClick, _              New EventHandler(AddressOf OnGreen)   AddHandler _blueButton.ServerClick, _              New EventHandler(AddressOf OnBlue) End Sub Protected Sub Page_Load(src As Object, e As EventArgs)   If Not IsPostBack Then     _color.Style("background-color") = "Red"     _color.Style("width") = "100"     _color.Style("height") = "100"   End If End Sub </script> <body>   <form runat=server>     <h2>ASP.NET color page</h2>     <div id=_color runat=server />     <p>     <input type=button id=_redButton value="Red"            runat=server />     <input type=button id=_greenButton value="Green"            runat=server />     <input type=button id=_blueButton value="Blue"            runat=server />     </p>   </form> </body> </html> 

Fortunately, ASP.NET does pass additional information with each POST request when server-side events are issued. In fact, there are two additional hidden fields on a form that uses server-side events like the one shown in Listing 2-7. The first field, __EVENTTARGET , is populated with the identifier of the control that generated the post-back, and the second field, __EVENTARGUMENT , is used to pass any parameters necessary to the event. These two hidden fields are populated in the client by using client-side JavaScript to trap the client-side event of the object and then issuing a post-back programmatically. When the POST is processed on the server, ASP.NET checks the contents of the __EVENTTARGET field and fires only events issued by the control whose ID is in that field. Listing 2-8 shows the client-side HTML generated by the color.aspx page shown in Listing 2-7.

Listing 2-8 Color Page Rendering
 <html><body>   <form name="_ctl0" method="post"         action="color.aspx" id="_ctl0"> <input type="hidden" name="__EVENTTARGET" value="" /> <input type="hidden" name="__EVENTARGUMENT" value="" /> <input type="hidden" name="__VIEWSTATE" value="dD...==" /> <script language="javascript"> <!--      function __doPostBack(eventTarget, eventArgument) {             var theform = document._ctl0;             theform.__EVENTTARGET.value = eventTarget;             theform.__EVENTARGUMENT.value = eventArgument;             theform.submit();      } // --> </script>     <h2>ASP.NET color page</h2>     <div id="_color"        style="background-color:Red;width:100;height:100;"/>     <p>     <input language="javascript"            onclick="__doPostBack('_redButton','')"            name="_redButton" id="_redButton"            type="button" value="Red" />     <input language="javascript"            onclick="__doPostBack('_greenButton','')"            name="_greenButton" id="_greenButton"            type="button" value="Green" />     <input language="javascript"            onclick="__doPostBack('_blueButton','')"            name="_blueButton" id="_blueButton"            type="button" value="Blue" />     </p>   </form> </body> </html> 

The server-side event model completes the Web Forms control model. Through the use of hidden fields, ASP.NET brings a familiar programming model to developers who are used to working with controls that issue events and render their current state, but may not be familiar with the disconnected HTTP protocol over which Web applications communicate.



Essential ASP.NET with Examples in Visual Basic .NET
Essential ASP.NET with Examples in Visual Basic .NET
ISBN: 0201760398
EAN: 2147483647
Year: 2003
Pages: 94
Authors: Fritz Onion

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net