Pro Server Controls and AJAX Components phần 6 potx

77 349 0
Pro Server Controls and AJAX Components phần 6 potx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

360 CHAPTER 8 ■ INTEGRATING CLIENT-SIDE SCRIPT set { ViewState["OverImageUrl"] = value; } } public bool PreLoadImages { get { object pre = ViewState["PreLoadImages"]; return (pre == null) ? true : (bool)pre; } set { ViewState["PreLoadImages"] = value; } } protected const string SWAP_FUNC = "__Image_Swap"; protected const string SWAP_ARRAY = "__Image_Swap_Array"; //@ symbol in front of the string preserves the layout of the string content protected const string SWAP_SCRIPT = @" function __Image_Swap(sName, sSrc) { document.images[sName].src = sSrc; } "; protected const string PRELOAD_SCRIPT = @" for (index = 0; index < {arrayname}; index++) { loadimg = new Image(); loadimg.src = {arrayname}[index]; } "; private bool renderClientScript = false; protected void DetermineRenderClientScript() { if (EnableClientScript && Context.Request.Browser.EcmaScriptVersion.Major >= 1) renderClientScript = true; } Cameron_865-2C08.fm Page 360 Monday, February 18, 2008 4:10 PM Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com CHAPTER 8 ■ INTEGRATING CLIENT-SIDE SCRIPT 361 protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); DetermineRenderClientScript(); if (renderClientScript) { // register the image-swapping JavaScript // if it is not already registered if (!Page.ClientScript.IsClientScriptBlockRegistered( typeof(RolloverImageLink), "SWAP_SCRIPT")) { Page.ClientScript.RegisterClientScriptBlock( typeof(RolloverImageLink), "SWAP_SCRIPT", SWAP_SCRIPT, true); } if (this.PreLoadImages) { // add image names to the // array of rollover images to be preloaded Page.ClientScript.RegisterArrayDeclaration( SWAP_ARRAY, "'" + ResolveUrl(this.ImageUrl) + "'," + "'" + ResolveUrl(this.OverImageUrl) + "'"); // register the image, preloading JavaScript // if it is not already registered if (!Page.ClientScript.IsStartupScriptRegistered( typeof(RolloverImageLink), "PRELOAD_SCRIPT")) { Page.ClientScript.RegisterStartupScript( typeof(RolloverImageLink), "PRELOAD_SCRIPT", PRELOAD_SCRIPT.Replace("{arrayname}", SWAP_ARRAY), true); } } } } Cameron_865-2C08.fm Page 361 Monday, February 18, 2008 4:10 PM Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 362 CHAPTER 8 ■ INTEGRATING CLIENT-SIDE SCRIPT protected override void Render(HtmlTextWriter writer) { // ensure the control is used inside <form runat="server"> Page.VerifyRenderingInServerForm(this); // set up attributes for the enclosing hyperlink // <a href></a> tag pair that go around the <img> tag writer.AddAttribute("href", this.NavigateUrl); // we have to create an ID for the <a> tag so that it // doesn't conflict with the <img> tag generated by // the base Image control writer.AddAttribute("name", this.UniqueID + "_href"); // emit onmouseover/onmouseout attributes that handle // client events and invoke our image-swapping JavaScript // code if client supports it if (renderClientScript) { writer.AddAttribute("onmouseover", SWAP_FUNC + "('" + this.UniqueID + "','" + ResolveUrl(this.OverImageUrl) + "');"); writer.AddAttribute("onmouseout", SWAP_FUNC + "('" + this.UniqueID + "','" + ResolveUrl(this.ImageUrl) + "');"); } writer.RenderBeginTag(HtmlTextWriterTag.A); // use name attribute to identify HTML <img> element // for older browsers writer.AddAttribute("name", this.UniqueID); base.Render(writer); writer.RenderEndTag(); } } } The RolloverImage Web Form The RolloverImage web form demonstrates the RolloverImageLink server control by adding two controls linked to large numeric images (1 and 2), as shown in Figure 8-2. Cameron_865-2C08.fm Page 362 Monday, February 18, 2008 4:10 PM Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com CHAPTER 8 ■ INTEGRATING CLIENT-SIDE SCRIPT 363 Figure 8-2. The RolloverImage web form When you hover over a button with the mouse, the image changes to a pushed down version, providing the nice effect shown in Figure 8-3. Figure 8-3. The RolloverImage web form on rollover Cameron_865-2C08.fm Page 363 Monday, February 18, 2008 4:10 PM Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 364 CHAPTER 8 ■ INTEGRATING CLIENT-SIDE SCRIPT If you click an image, the page will navigate either to the publisher’s site or to the ASP.NET web site. The full code for the web form is shown in Listings 8-5 and 8-6. Listing 8-5. The RolloverImage Web Form .aspx Page File <%@ Page Language="C#" MasterPageFile="~/MasterPage/ControlsBook2MasterPage.Master" AutoEventWireup="true" CodeBehind="RolloverImage.aspx.cs" Inherits="ControlsBook2Web.Ch08.RolloverImage" Title="RolloverImage Demo" %> <%@ Register Assembly="ControlsBook2Lib" Namespace= "ControlsBook2Lib.Ch08" TagPrefix="apress" %> <asp:Content ID="Content1" ContentPlaceHolderID="HeadSection" runat="server"> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="ChapterNumAndTitle" runat="server"> <asp:Label ID="ChapterNumberLabel" runat="server" Width="14px">8</asp:Label>&nbsp;&nbsp;<asp:Label ID="ChapterTitleLabel" runat="server" Width="360px"> Integrating Client-Side Script</asp:Label> </asp:Content> <asp:Content ID="Content3" ContentPlaceHolderID="PrimaryContent" runat="server"> <apress:RolloverImageLink ID="image1" runat="server" ImageUrl="ex1.gif" OverImageUrl="ex1_selected.gif" NavigateUrl="http://www.apress.com" /> <apress:RolloverImageLink ID="image2" runat="server" ImageUrl="ex2.gif" OverImageUrl="ex2_selected.gif" NavigateUrl="http://asp.net" EnableClientScript="True" /><br /> </asp:Content> Listing 8-6. The RolloverImage Web Form Code-Behind Class File using System; namespace ControlsBook2Web.Ch08 { public partial class RolloverImage : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } } } Cameron_865-2C08.fm Page 364 Monday, February 18, 2008 4:10 PM Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com CHAPTER 8 ■ INTEGRATING CLIENT-SIDE SCRIPT 365 Analyzing the Rollover HTML Output The rollover functionality lives in the emitted hyperlink tags in the HTML output. The top of the HTML form also contains the image-swapping function called by the onmouseover and onmouseout client event handlers attached to the hyperlinks, as shown here: <script type="text/javascript"> <! function __Image_Swap(sName, sSrc) { document.images[sName].src = sSrc; } // > </script> The Image control output shows the <img> tags wrapped by an <a> tag and the client-script event mappings for onmouseover and onmouseout: <a href="http://www.apress.com" name="ctl00$ControlsBookContent$image1_href" onmouseover="__Image_Swap('ctl00$ControlsBookContent$image1', '/ControlsBook2Web/Ch08/ex1_selected.gif');" onmouseout= "__Image_Swap('ctl00$ControlsBookContent$image1', '/ControlsBook2Web/Ch08/ex1.gif');"><img name="ctl00$ControlsBookContent$image1" id="ctl00_ControlsBookContent_image1" src="ex1.gif" style="border-width:0px;" /></a> <a href="http://asp.net" name="ctl00$ControlsBookContent$image2_href" onmouseover="__Image_Swap('ctl00$ControlsBookContent$image2', '/ControlsBook2Web/Ch08/ex2_selected.gif');" onmouseout= "__Image_Swap('ctl00$ControlsBookContent$image2', '/ControlsBook2Web/Ch08/ex2.gif');"><img name= "ctl00$ControlsBookContent$image2" id="ctl00_ControlsBookContent_image2" src="ex2.gif" style="border-width:0px;" /></a> At the bottom of the HTML document is the code to preload the images. It creates the Image JavaScript object and sets the src attribute to complete its task. One script block is emitted for each control to initialize its images: <script type="text/javascript"> <! var __Image_Swap_Array = new Array('/ControlsBook2Web/Ch08/ex1.gif','/ ControlsBook2Web/Ch08/ex1_selected.gif', '/ControlsBook2Web/Ch08/ex2.gif', '/ControlsBook2Web/Ch08/ex2_selected.gif'); // > </script> <script type="text/javascript"> <! Cameron_865-2C08.fm Page 365 Monday, February 18, 2008 4:10 PM Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 366 CHAPTER 8 ■ INTEGRATING CLIENT-SIDE SCRIPT for (index = 0; index < __Image_Swap_Array; index++) { loadimg = new Image(); loadimg.src = __Image_Swap_Array[index]; } // > </script> Running a Client Script When a Form Is Submitted The previous section showed how to run client script at load time of the HTML document via the RegisterStartupScript method in the ClientScriptManager class. In this section, we discuss how to execute a client script just after postback is initiated by the end user, whether through a button click or through a JavaScript-based method. We create two custom server controls to assist in presenting the concepts required to execute client script when a form is submitted. The first server control we discuss is the FormConfirmation control. The FormConfirmation Control FormConfirmation is a server control designed to display a message when the browser is ready to submit the HTML document back to the web server. We inherit from System.Web.UI.Control, because we do not have a UI to display and, therefore, do not need the styling and device- rendering features of System.Web.UI.WebControls.WebControl. Listing 8-7 provides the source code for the FormConfirmation server control. ASP.NET allows you to add code to the onsubmit event attribute of the <form> tag generated by the web form via the RegisterOnSubmitStatement method in the ClientScriptManager class. This hooks into the normal HTTP posting mechanism, as we describe in Chapter 5. Listing 8-7. The FormConfirmation Server Control using System; using System.Web; using System.Web.UI; using System.ComponentModel; namespace ControlsBook2Lib.Ch08 { [ToolboxData("<{0}:FormConfirmation runat=server></{0}:FormConfirmation>"), DefaultProperty("Message")] public class FormConfirmation : Control { public virtual string Message { get { return (string)ViewState["Message"]; } Cameron_865-2C08.fm Page 366 Monday, February 18, 2008 4:10 PM Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com CHAPTER 8 ■ INTEGRATING CLIENT-SIDE SCRIPT 367 set { ViewState["Message"] = value; } } protected override void OnPreRender(EventArgs e) { if (Context.Request.Browser.EcmaScriptVersion.Major >= 1) { string script = "return (confirm('" + this.Message + "'));"; // register JavaScript code for onsubmit event // of the HTML <form> element Page.ClientScript.RegisterOnSubmitStatement(typeof(FormConfirmation), "FormConfirmation", script); } } protected override void Render(HtmlTextWriter writer) { // make sure the control is rendered inside // <form runat=server> tags Page.VerifyRenderingInServerForm(this); base.Render(writer); } } } FormConfirmation exposes a Message property to allow web developers to customize the JavaScript confirmation prompt to the end user. This simple control takes advantage of the ClientScriptManager class’s RegisterOnSubmitStatement method we described previously to properly inject the script into the HTML stream loaded in the browser. Just drop the control on a web form, and voilà! You can confirm that the user is ready to proceed with submitting the form back to the server. If the user does not affirm the form submission, the script cancels the action by returning false. The other item to highlight for this control is the Render override for the purposes of ensuring the control is located inside a web form via the Page class’s VerifyRenderingInServerForm method. In the next section, we discuss an interesting variation on this theme of confirming navi- gation away from a page by adding the capability of checking whether a user wants to move on to a new page or stay on the current web form. The ConfirmedLinkButton Control The ConfirmedLinkButton button prompts with a custom message that will not navigate if the user cancels the action. ConfirmedLinkButton does not use the RegisterOnSubmitStatement of the ClientScriptManager class; rather, it uses the client-side postback system of ASP.NET. Cameron_865-2C08.fm Page 367 Monday, February 18, 2008 4:10 PM Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 368 CHAPTER 8 ■ INTEGRATING CLIENT-SIDE SCRIPT We use this control on a web form in conjunction with the previously created FormConfirmation control to show how the two mechanisms interact. The source code for the ConfirmedLinkButton server control is provided in Listing 8-8. ConfirmedLinkButton exposes a Message property like FormConfirmation, but it differs in that it inherits from the LinkButton control. LinkButton renders as a hyperlink but submits the web form via JavaScript. Listing 8-8. The ConfirmedLinkButton Server Control using System; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Text; using System.ComponentModel; namespace ControlsBook2Lib.Ch08 { [ToolboxData("<{0}:ConfirmedLinkButton runat=server></{0}:ConfirmedLinkButton>"), DefaultProperty("Message")] public class ConfirmedLinkButton : LinkButton { private string message = ""; public virtual string Message { get { return message; } set { message = value; } } protected override void AddAttributesToRender(HtmlTextWriter writer) { // enhance the LinkButton by replacing its // href attribute while leaving the rest of the // rendering process to the base class if (Context != null && Context.Request.Browser.EcmaScriptVersion.Major >= 1 && this.Message != "") { StringBuilder script = new StringBuilder(); script.Append("javascript: if (confirm('"); script.Append(this.Message); script.Append("')) {"); // get the ASP.NET JavaScript that does a form // postback and have this control submit it script.Append(Page.ClientScript.GetPostBackEventReference(this, "")); script.Append("}"); writer.AddAttribute(HtmlTextWriterAttribute.Href, script.ToString()); Cameron_865-2C08.fm Page 368 Monday, February 18, 2008 4:10 PM Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com CHAPTER 8 ■ INTEGRATING CLIENT-SIDE SCRIPT 369 } } } } We override the AddAttributesToRender method so that we can change the normal href attribute content to add a call to the JavaScript confirm method instead. Because we override the href attribute, we use the GetPostBackEventReference method to set up postback; otherwise, the form submission mechanism will not fire. GetPostBackEventReference obtains a reference to a client-side script function that causes the server to post back to the page. Because this control is inheriting from an existing WebControl, we do not need to call Page.VerifyRenderingInServerForm, because this call is already performed by the base class implementation of LinkButton. In the next section, we test the behavior of the ConfirmedLinkButton and FormConfirmation server controls in the Confirm web form demonstration .aspx page. The Confirm Web Form The interaction between the client form submission event and the code emitted by controls to perform JavaScript postbacks for ASP.NET is not as integrated as we would like. The core problem is that the onsubmit client event is not fired if the HTML form is submitted programmatically via JavaScript. To demonstrate the need for better integration, the Confirm web form hosts a set of form posting controls. On the Confirm web form are a regular ASP.NET Button that does a traditional HTML form post and an ASP.NET LinkButton that uses JavaScript from ASP.NET to cause a postback. We also have our FormConfirmation and ConfirmedLinkButton server controls to show how they provide confirmation on form submit in their own unique manner. Figure 8-4 shows the static web form display output. Figure 8-4. The Confirm web form Cameron_865-2C08.fm Page 369 Monday, February 18, 2008 4:10 PM Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com [...]... Client-Side and Server- Side Events The event processing that occurs in the client browser is separate from the ASP.NET activity that occurs on the server to generate HTML output and respond to server- side events In this section, we build an example server control that provides seamless integration of the two event models in a similar manner to the built-in ASP.NET Validator controls client-side and serverside... Increment, and Value The UpDown server control exposes four properties that allow developers to configure its behavior in the Visual Studio Designer: MinValue, MaxValue, Increment, and Value The property handlers perform data validation tasks to ensure the number set for the Value property falls between the MinValue and MaxValue property range We default to System.Int.MaxRange for the MaxValue property... client-side programming and server controls along with graceful down-level client rendering, we construct a server control that mimics the NumericUpDown control from the Windows Forms desktop NET development environment; our control is shown in Figure 8-8 The UpDown server control takes the form of a composite control with a TextBox to hold the value and two Buttons with the captions + and – to represent up and. .. describe how the control is constructed Accessing UpDown Child Controls UpDown is a composite server control that declares private controls of type TextBox to render an tag and two Button controls to render tags It adds these controls by overriding the CreateChildControls method from WebControl, and it wires up their events to the parent control’s events Because... value are handled by the composite control and how the control dynamically determines whether or not to fire server- side events Handling Child Control Events We glossed over the fact that we mapped the button-click events to server- side handlers in our composite UpDown control They are not necessary if we assume the browser can handle the client-side script The client-side onclick event fully handles the... Page.ClientScript.RegisterClientScriptResource(typeof(UpDown), "ControlsBook2Lib.Ch08.UpDown.js"); } } public override ControlCollection Controls { get { EnsureChildControls(); return base .Controls; } } protected override void CreateChildControls() { Controls. Clear(); // add the textbox that holds the value valueTextBox = new TextBox(); valueTextBox.ID = "InputText"; valueTextBox.Width = 40; valueTextBox.Text = "0"; Controls. Add(valueTextBox);... Event Our server control makes it easy to monitor the UpDown control and be notified only when it changes value through a server- side event named ValueChanged The ValueChanged event is raised when it detects a difference between the Value property of the control from ViewState and what is received from the client after a postback: public event EventHandler ValueChanged { add { Events.AddHandler(ValueChangedKey,... receive postback handling // to properly handle child input controls Page.RegisterRequiresPostBack(this); 379 Simpo PDF MergePage 380 Split Unregistered PM Cameron_ 865 -2C08.fm and Monday, February 18, 2008 4:10 Version - http://www.simpopdf.com 380 CHAPTER 8 ■ INTE GRATIN G CLIENT-SIDE SC RIPT if (renderClientScript) { // register the block that does the // client-side handling Page.ClientScript.RegisterClientScriptResource(typeof(UpDown),... } return changed; } void IPostBackDataHandler.RaisePostDataChangedEvent() { OnValueChanged(EventArgs.Empty); } public event EventHandler ValueChanged { add { Events.AddHandler(ValueChangedKey, value); } remove { Events.RemoveHandler(ValueChangedKey, value); } } protected virtual void OnValueChanged(EventArgs e) { EventHandler valueChangedEventDelegate = (EventHandler) Events[ValueChangedKey]; if (valueChangedEventDelegate... ensure we receive postback handling // to properly handle child input controls Page.RegisterRequiresPostBack(this); Simpo PDF MergePage 391 Split Unregistered PM Cameron_ 865 -2C08.fm and Monday, February 18, 2008 4:10 Version - http://www.simpopdf.com CHAPTER 8 ■ IN TEG RATING CLIENT-SIDE SC RIPT if (renderClientScript) { // register the block that does the // client-side handling Page.ClientScript.RegisterClientScriptResource(typeof(UpDown), . RolloverImageLink server control by adding two controls linked to large numeric images (1 and 2), as shown in Figure 8-2. Cameron_ 865 -2C08.fm Page 362 Monday, February 18, 2008 4:10 PM Simpo PDF Merge and. Client-Side and Server- Side Events The event processing that occurs in the client browser is separate from the ASP.NET activity that occurs on the server to generate HTML output and respond to server- side. UpDown server control has a number of important properties that we discuss in the next section. Key Properties: MinValue, MaxValue, Increment, and Value The UpDown server control exposes four properties

Ngày đăng: 12/08/2014, 23:20

Từ khóa liên quan

Mục lục

  • Pro ASP.NET 3.5 Server Controls and AJAX Components

  • Contents at a Glance

  • Contents

  • About the Authors

  • About the Technical Reviewer

  • Acknowledgments

  • Introduction

    • Who This Book Is For

    • How This Book Is Structured

    • Prerequisites

    • Downloading the Code

    • Contacting the Authors

    • Server Control Basics

      • Source Code

      • The Heart and Soul of ASP.NET

      • A .NET Framework fiHelo, WorldflWeb Form

      • Control Properties

      • Control Methods

      • Control Events

      • The Web Page As a Control Tree

      • The Root Controls

        • The System.Web.UI Namespace

        • System.Web.UI.HtmlControls Namespace

          • An HTML Controls Demonstration

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan