Mapping a Postback Event to a Server Event The IPostBackEventHandler Interface

Interface"-->

Mapping a Postback Event to a Server Event ” The IPostBackEventHandler Interface

We'll now examine the event architecture that enables a server control to map a client-side event into a corresponding server-side event. To develop a control that raises events in response to postback, you must implement the System.Web.UI.IPostBackEventHandler interface, which contains one method:

 publicinterfaceIPostBackEventHandler{ voidRaisePostBackEvent(stringeventArgument); } 

The argument that the page passes into this method is useful if your control renders multiple HTML elements that cause postback events. In this section, we will look at controls that render a single postback element. We'll show an example that uses this argument in "Rendering Multiple Elements That Use Client Script for Postback ”The NavButtons Example."

Upon postback, the page searches its control tree for a control whose UniqueID matches the name of the element that caused postback. (Later in this section, we'll show you how your control can cause the UniqueID to appear in the posted form data.) If the page finds a matching control and that control implements IPostBackEventHandler , the page invokes the control's RaisePostBackEvent method. If your control cannot render its UniqueID as the name attribute of a form element ”which means that its UniqueID does not appear in the posted form data ” there is an alternate way to ensure that your control is invoked by the page during the Raise Postback Event phase. To do this, your control must invoke the RegisterRequiresPostBack method of the containing page, as we'll show in the Login example at the end of this chapter.

The RaisePostBackEvent method is where you implement the logic that your control should perform on postback. In general, a control will raise one or more server-side events in the RaisePostBackEvent method. For example, the Button control raises the Click event from its RaisePostBackEvent method. To make the discussion concrete, we'll now develop a SimpleButton control that is similar to the ASP.NET Button control.

Implementing IPostBackEventHandler ” The SimpleButton Example

The SimpleButton control implements the IPostBackEventHandler interface and raises a server-side Click event in response to postback. In Chapter 3, we described the event architecture in the .NET Framework and provided an example that walks through the steps of exposing an event from a class. Implementing an event in a server control is no different from implementing an event in any other managed class. The implementation of the Click event in SimpleButton follows the standard event pattern that we described in Chapter 3 ”an event member named Click and an OnClick method that raises the event. If you have not implemented .NET events, you should look at the section "Raising an Event" in Chapter 3 because, throughout the rest of the book, we assume that you are familiar with the basics of raising an event from a class.

Listing 9-3 contains the code for the SimpleButton control. The highlighted code provides the functionality to map a postback event into a server event. We'll discuss the example after the code listing.

Listing 9-3 SimpleButton.cs
 usingSystem; usingSystem.ComponentModel; usingSystem.Web.UI; usingSystem.Web.UI.WebControls; namespaceMSPress.ServerControls{ [//TheDefaultEventAttributeallowsapage //developertoattachahandlertothedefault //eventbydouble-clickingonthecontrol. 
 DefaultEvent("Click"), DefaultProperty("Text")] publicclassSimpleButton:WebControl,  IPostBackEventHandler  { [Bindable(true), Category("Behavior"), DefaultValue(""), Description("Thetexttodisplayonthebutton")] publicvirtualstringText{ get{ strings=(string)ViewState["Text"]; return((s==null)?String.Empty:s); } set{ ViewState["Text"]=value; } } protectedoverrideHtmlTextWriterTagTagKey{ get{ returnHtmlTextWriterTag.Input; } } [Category("Action"),Description("Raisedwhenthebuttonisclicked")] publiceventEventHandlerClick; protectedoverridevoidAddAttributesToRender(HtmlTextWriterwriter){ base.AddAttributesToRender(writer);  writer.AddAttribute(HtmlTextWriterAttribute.Name,this.UniqueID);  writer.AddAttribute(HtmlTextWriterAttribute.Type,"Submit"); writer.AddAttribute(HtmlTextWriterAttribute.Value,this.Text); } //MethodofIPostBackEventHandlerthatraisespostbackevents.  voidIPostBackEventHandler.RaisePostBackEvent(stringeventArgument){ OnClick(EventArgs.Empty); }  //InvokesdelegateregisteredwiththeClickevent. protectedvirtualvoidOnClick(EventArgse){ if(Click!=null){ Click(this,e); } } protectedoverridevoidRender(HtmlTextWriterwriter){ //Makesurethiscontrolisnestedinaform.  if(Page!=null){ Page.VerifyRenderingInServerForm(this); }  base.Render(writer); } } } 

SimpleButton demonstrates the following tasks , which are essential for implementing postback event functionality:

  • Implements IPostBackEventHandler .

  • Raises the Click event in the RaisePostBackEvent method by invoking the OnClick method. In effect, this maps the client-side submit event to a server-side Click event.

  • Renders an HTML name attribute whose value is the UniqueID of the control. The UniqueID of the control is assigned to it by the page and is guaranteed by the page framework to be unique on the page. The page generates the UniqueID based on the control's user -assigned (or autogenerated by the page) ID property. By assigning the value of the UniqueID to the name attribute, you ensure that your control renders an element whose name is unique in the form post data and that the page can route the postback event to your control.

In addition, SimpleButton invokes ”from its Render method ”the Verify ­RenderingInServerForm method of the page to ensure the page developer uses the control in a server-side form (<form runat ="server"> </form> ). The Verify ­RenderingInServerForm method causes the page to throw an exception if the page developer does not place the control within server-side form tags. The page framework requires that form controls must be nested within a server-side form to ensure that the name/value pairs for the rendered HTML elements are part of the form data posted by the browser. In general, if your control renders a form input element, you should include the call to VerifyRenderingInServerForm .

SimpleButton also demonstrates a feature that is not specific to ASP.NET but is a feature of the C# programming language ” explicit interface method implementation , also known as private interface method implementation . Explicit interface method implementation in effect allows you to implement a method of an interface without adding the method to the public object model of your class. This is in contrast to standard interface implementation, which requires that interface methods must have public access in a class that implements the interface. An explicitly implemented interface method is not really private ”it can be accessed from outside the class. However, the class that implements this interface method must be cast into the interface type before the method can be invoked. Thus, if simpleButton1 is an instance of SimpleButton , (IPostBackEventHandler)simpleButton1.RaisePostBackEvent(eventArgument) is allowed, but simpleButton1.RaisePostBackEvent(eventArgument) is not.

To explicitly implement an interface method, you must qualify the name of the method with the name of the interface. In addition, you cannot provide any modifiers, such as private , protected , or virtual . Here's an example of explicit interface method implementation from the SimpleButton control:

 void  IPostBackEventHandler.  RaisePostBackEvent(stringeventArgument){ OnClick(EventArgs.Empty); } 

Listing 9-4 contains a page that uses the SimpleButton control and attaches an event handler to its Click event. Figures 9-4 and 9-5 show the page viewed in a browser before and after postback.

Listing 9-4 SimpleButtonTest.aspx
 <%@PageLanguage="C#"%> <%@RegisterTagPrefix="msp"Namespace="MSPress.ServerControls" Assembly="MSPress.ServerControls"%> <html> <head> <scriptrunat="server"> voidsimpleButton1_Click(objectsender,EventArgse){ label1.Text="Youclickedthebutton."; } </script> </head> <body> <formrunat="server"> <br> Clickthebuttontoraiseitsserver-sideClickevent. <br> <msp:SimpleButtonText="Submit"Runat="server" 
 OnClick="simpleButton1_Click"id="simpleButton1"/> <br> <asp:LabelFont-Size="10pt"Font-Bold="true"id="label1" runat="server"/> </form> </body> </html> 
Figure 9-4. SimpleButtonTest.aspx viewed in a browser on initial request

graphics/f09hn04.jpg

Figure 9-5. SimpleButtonTest.aspx viewed in a browser after postback

graphics/f09hn05.jpg



Developing Microsoft ASP. NET Server Controls and Components
Developing Microsoft ASP.NET Server Controls and Components (Pro-Developer)
ISBN: 0735615829
EAN: 2147483647
Year: 2005
Pages: 183

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