Tài liệu ASP.NET 1.1 Insider Solutions- P7 pptx

50 489 0
Tài liệu ASP.NET 1.1 Insider Solutions- P7 pptx

Đ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

If (ScrollBars = True) Then sScroll = “yes” End If Dim sHelp As String = “no” If (HelpButton = True) Then sHelp = “yes” End If Because a couple of the features for dialog windows are available only in Internet Explorer 5.5 and higher, you next use the BrowserCapabilities object (exposed by the ASP.NET Request. Browser property) to check the browser type and version (see Listing 7.24). You create a Decimal (floating-point) value that contains the major and minor version numbers. Then, provided that you haven’t already done so in a previous instance of the control, you build the client-side script in a String variable (as you’ve done in previous examples). The client- side script here appears to be a bit more complex than that in earlier examples because you have to create the features string as you go along. When the script is complete, you can create the function name and parameters string and attach the whole thing to the target control in exactly the same way as in the two previous examples (the code for this is not repeated here; refer to Listing 7.15). LISTING 7.24 Sniffing the Browser Type and Creating the Client-Side Script ‘ get browser version, but only if it’s Internet Explorer Dim fVer As Decimal = 0 If Request.Browser.Browser = “IE” Then Try Dim iMajor As Integer = Request.Browser.MajorVersion Dim iMinor As Integer = Request.Browser.MinorVersion fVer = Decimal.Parse(iMajor.ToString() & “.” _ & iMinor.ToString()) Catch End Try End If ‘ create client-side script if not already registered If Not Page.IsClientScriptBlockRegistered(“AHHIEDlg”) Then ‘ decide whether position is specified or centered If (Center = True) Then sFeatures = “center:yes;” Else sFeatures = “dialogTop:” & Top.ToString() _ & “px;dialogLeft:” & Left.ToString() & “px;” End If 7 Design Issues for User Controls 288 LISTING 7.23 Continued 10 0672326744 CH07 5/4/04 12:26 PM Page 288 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 289 Integrating Internet Explorer Dialog Windows sFeatures &= “dialogHeight:” & Height.ToString() _ & “px;dialogWidth:” & Width.ToString() _ & “px;edge:” & sBorder & “;scroll:” _ & sScroll & “;help:” & sHelp & “;” ‘see if it’s IE 5.5 or higher If fVer >= 5.5 Then sFeatures &= “resizable:” & sResize _ & “;status:” & sStatus & “;” End If sScript = “<script language=’javascript’>” & vbCrlf _ & “<! ” & vbCrlf _ & “function IEDlgEvent(sURL, sArgs, sFeatures, sField,” _ & “ bSubmit) {“ & vbCrlf _ & “ var oHidden = document.getElementById(sField);” & vbCrlf _ & “ oHidden.value = window.showModalDialog(sURL, sArgs,” _ & “ sFeatures)” & vbCrlf _ & “ return bSubmit;” & vbCrlf _ & “}” & vbCrlf _ & “// >” & vbCrlf _ & “<” & “/script>” & vbCrlf Page.RegisterClientScriptBlock(“AHHIEDlg”, sScript) End If ‘ create function name to attach to control ‘ must escape any single quotes in agruments string Dim sArgs As String = Arguments.Replace(“‘“, “\’”) Dim sFunctionName As String = “return IEDlgEvent(‘“ _ & SourceURL & “‘, ‘“ & sArgs & “‘, ‘“ _ & sFeatures & “‘, ‘“ & sHidFieldName & “‘, “ _ & (Not CancelEvent).ToString().ToLower() & “);” ‘ attach client-side event handler to element as in previous examples To make it easier to see the result, the client-side script function named IEDlgEvent that is gener- ated and injected into the page is shown in Listing 7.25. It takes as parameters the URL of the page to display, the arguments string to pass to the dialog, the features string, the name of the hidden control where the return value will be placed, and a Boolean value that specifies whether the underlying control event will be canceled. You can see that the return value from the showModalDialog method is simply placed into the hidden control when the dialog is closed, and the value of the bSubmit parameter is returned to the underlying control. LISTING 7.24 Continued 10 0672326744 CH07 5/4/04 12:26 PM Page 289 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. LISTING 7.25 The Client-Side IEDlgEvent Function That Is Generated by the User Control function IEDlgEvent(sURL, sArgs, sFeatures, sField, bSubmit) { var oHidden = document.getElementById(sField); oHidden.value = window.showModalDialog(sURL, sArgs, sFeatures) return bSubmit; } The IEDlgEvent function, shown in Listing 7.25, is called by the event handler attribute attached to the target control—which, depending on the property settings made in the main page, should look something like this: return IEDlgEvent(‘dialogpage.aspx’, ‘S’, ‘center:yes; dialogHeight:300px;dialogWidth:500px;edge:Sunken;scroll:yes; help:yes;resizable:no;status:no;’, ‘AHHIEDlg$test1’, true); Returning a Value from the Modal Dialog The final issue to consider in the sample page is how to get the value selected in the dialog page back to the main page. In fact, all you need to do is assign it to the returnValue property of the window object that is hosting the main page and then close the dialog window by calling its close method: window.returnValue = sMyReturnVal; window.close(); The value assigned to the returnValue property then appears as the return value of the call to the showModalDialog method that originally opened the dialog window. Browser-Adaptive Dialog Windows As you discovered in the earlier examples in this chapter, it’s possible to build user controls that automatically adapt to suit different browsers. The following sections show you how to build a version of the Internet Explorer dialog window example that works in a similar way in other browsers. The sample page that contains the options you can set is shown in Figure 7.13, and you can see that the one extra property is ModalDialog , which you can set to True or False . When ModalDialog is set to True and the page is viewed in Internet Explorer, the result is the same as that in the previous example. A modal Internet Explorer dialog window is shown. If you change ModalDialog to False or view the page in a different browser, it seems at first that the result is the same (see Figure 7.14). However, this is actually a new browser window instance and not a modal dialog. By setting the appropriate features when you call the standard window.open method (which all browsers support), you get a similar appearance. 7 Design Issues for User Controls 290 10 0672326744 CH07 5/4/04 12:26 PM Page 290 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 291 Browser-Adaptive Dialog Windows However, one major difference in this case is that you can no longer easily provide automatic postback (although it is possible, as you’ll see later in this chapter). The new window executes separately from the main window. However, you use script in the new window to insert the value the user selects into the hidden control in the main window, so it can be collected on a postback from the main window (exactly as shown in Figure 7.12). You just click the Get Result button after selecting a value (which closes the new window) to see this occur. How the Browser-Adaptive Dialog Window Example Works Much of the code in this example is the same as the code for the previous example. These are the important points where it differs: n In this example, you have to detect the browser type as before, but this time, you have to determine whether it is Internet Explorer or some other browser. n If the browser type is not Internet Explorer, you generate a features string that uses the syntax and names specific to the window.open method rather than to the window. showModalDialog method. Here’s an example: “top=150,left=150,height=320,width=500,scrollbars=yes, resizable=no,status=no,titlebar=yes,menubar=no,location=no, fullscrceen=no,toolbar=no,directories=no” FIGURE 7.13 The browser-adaptive dialog window sample page. FIGURE 7.14 The nonmodal (new window) dialog page. 10 0672326744 CH07 5/4/04 12:26 PM Page 291 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. n You must generate and inject a different client-side script function, which calls the window.open method rather than the window.showModalDialog method. In addition, when using the window.open method, you can’t assign the return value to the hidden control. n There is no arguments parameter for the window.open method, but you need to pass the optional argument to the new window. So that the dialog page can work in both versions, you append this value to the URL of the new page as a query string for both the window.open method and the window.showModalDialog method. You can extract it from the Request.QueryString collection within the new page by using the GetWindowArgument method (which is described shortly). These are the two functions you generate to open a new browser window and a modal dialog window: function IEDlgEvent(sURL, sArgs, sFeatures, sField, bSubmit) { window.open(sURL + ‘?arg=’ + escape(sArgs), ‘_blank’, sFeatures); return false; } function IEDlgEvent(sURL, sArgs, sFeatures, sField, bSubmit) { var oHidden = document.getElementById(sField); oHidden.value = window.showModalDialog(sURL + ‘?arg=’ + escape(sArgs), ‘’, sFeatures); return bSubmit;” & vbCrlf _ n You have to use a different technique in a new browser window to get the selected value back to the main window and then close the new window. You’ll see how this is achieved in the following section. As with the modal dialog window example, this chapter doesn’t list all the code for the page you see displayed in the new window (the list of customers). However, this example uses server- side (ASP.NET) data binding rather than the Internet Explorer–specific client-side data binding approach used in the modal window in the previous example. This means that the dialog page will work on non–Internet Explorer browsers as well as in Internet Explorer. You can use the [view source] link at the bottom of the page in the dialog window to see this code if you wish. Returning a Value from the New Window When you open a new browser window to act as a dialog, there is no facility to specify an optional arguments parameter when opening the window or for returning a value to the main window directly (as is possible with the Internet Explorer showModalDialog method). Instead, you expose two extra methods from this version of the user control, which are designed to be used in the page that is displayed in the dialog window. Using these methods means that you have to register the user control in the page that you show in the dialog window, as well as in the main page. Listing 7.26 shows the two methods. The GetWindowArgument method takes the ID of the control that the script for opening the dialog or new window was attached to, and it simply extracts the value from the Request.QueryString collection where it was placed by the client-side code that opened the dialog or new window. Recall that you pass the value in the query string in all cases, 7 Design Issues for User Controls 292 10 0672326744 CH07 5/4/04 12:26 PM Page 292 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 293 Browser-Adaptive Dialog Windows even when using the showModalDialog method because it is the only obvious way to allow the same page to work in the dialog window for all types of browsers. LISTING 7.26 The GetWindowArgument and SetWindowResult Methods Function GetWindowArgument(ControlID As String) As String ‘ get posted value from Request collection Return Server.UrlDecode(Request.QueryString(“arg”)) End Function Sub SetWindowResult(ControlID As String, ReturnValue As String) ‘ build hidden field name Dim sHidFieldName As String = “AHHIEDlg$” & ControlID ‘ create client-side script Dim sScript As String sScript = “<script language=’javascript’>” & vbCrlf _ & “<! ” & vbCrlf _ & “if (opener != null) {“ & vbCrlf _ & “ var oHidden = window.opener.document.forms[0]” _ & “ .elements[‘“ & sHidFieldName & “‘];” & vbCrlf _ & “ if (oHidden != null)” & vbCrlf _ & “ oHidden.value = ‘“ & ReturnValue & “‘;” & vbCrlf _ & “ }” & vbCrlf _ & “else” & vbCrlf _ & “ window.returnValue = ‘“ & ReturnValue & “‘;” & vbCrlf _ & “window.close();” & vbCrlf _ & “// >” & vbCrlf _ & “<” & “/script>” & vbCrlf Page.RegisterStartupScript(“AHHDlgReturn”, sScript) End Sub The SetWindowResult method, called within the dialog or new window page, accepts the ID of the control that the script to open the dialog or new window was attached to and the value to be returned to the main page. You first check the opener property of the current window to see if it contains a valid reference to the main page window that opened this window. If it does, this provides a reference to the window object where the code that opened the new window was located. You can reference the hidden control in that window and insert the return value into it. If the opener property is null , you know that the current window is a modal dialog window that was opened with the showModalDialog method. In this case, you can simply set the returnValue property of the current window. This value will automatically be returned to the main window and inserted into the hidden control by the code there that called the showModalDialog method. Then, in either case, you just have to call the close method of this window. The result is that the new window closes, and the value is available in the main page when the next postback 10 0672326744 CH07 5/4/04 12:26 PM Page 293 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. occurs. As with the earlier examples, it can be extracted at this point, using the same GetDialogResult function that is exposed by all the versions of this user control. The RegisterStartupScript Method Notice that you build the script code as a String in the SetWindowResult method and then insert it into the page by using the RegisterStartupScript method rather than the RegisterClientScriptBlock method used in other examples. The RegisterClientScriptBlock method is designed to insert complete functions into a page so that they can be called from control event handler attributes (as is done in earlier examples). The script section is inserted into the page at the start of the server-side form section, immediately after the opening <form> element. The RegisterStartupScript method is designed to inject into the page client-side code that is not a function. If you refer to Listing 7.26, you’ll see that you inject inline code that will run as the page loads, following the postback. This is how the code inserts the return value into the hidden control on the main page and then closes the new window. This kind of code is often referred to as a startup script, and hence the ASP.NET method is called RegisterStartupScript . For the startup script to work properly, the best location is at the end of the page. The RegisterStartupScript method actually injects it at the end of the server-side form section, just before the closing <form> element. Because the controls it references are likely to be on the form, this will work fine in most cases. The corresponding method named IsStartupScriptRegistered can be used to check whether this script section has already been registered (that is, already injected into the page). Summary This chapter concentrates on user controls and how you can take advantage of many of the features they offer to build reusable content that can implement useful controls or methods in a range of types of browsers. This chapter starts by looking at how user controls affect the design and implementation of your code and user interface. The main issue here is coping with the possibility that the control may be used more than once in the same page, and there are techniques and features of ASP.NET that help you to manage this. In particular, you can easily prevent duplicate script sections from being injected into a page. Then, to focus more closely on techniques for building user controls, this chapter shows how you can convert the MaskedEdit control you created in Chapter 6 into a user control. Along the way, this chapter looks at issues such as referencing separate script and image files and adding client-side and server-side validation with the ASP.NET validation controls. 7 Design Issues for User Controls 294 Implementing AutoPostback when the Dialog Window Closes If you want to provide automatic postback when the new window is closed, you can achieve this by adding code to the script injected by the SetWindowResult method. All you need to do is call the submit method of the form on the main page before you call the close method of the new window. 10 0672326744 CH07 5/4/04 12:26 PM Page 294 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 295 Summary Next, this chapter shows how to build a new user control—a SpinBox control—from scratch. While many of the techniques are the same as you used for the MaskedEdit control, this chapter looks at things like checking property value settings, throwing exceptions, and implementing AutoPostback from a composite control. The remainder of this chapter concentrates on a series of examples that have no visible user interface yet make it easy for you to add useful features to Web applications by taking advantage of client-side dialog boxes and dialog windows. While some of the features are specific to Internet Explorer, this chapter shows how you can quite easily build controls that adapt to different types of browsers. This last technique described in this chapter—providing graceful fallback for browsers that don’t implement features you want to take advantage of—leads neatly in to Chapter 8. You’ve already learned about and built a couple of these browser-adaptive controls, and you’ll see a lot more on this topic in Chapter 8. In particular, you’ll extend the SpinBox control introduced in this chapter into a full-fledged browser-adaptive server control. 10 0672326744 CH07 5/4/04 12:26 PM Page 295 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 10 0672326744 CH07 5/4/04 12:26 PM Page 296 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 8 Building Adaptive Controls The previous three chapters discuss differ- ent ways to provide useful reusable content for Web sites and Web applications, while taking advantage of the features of more recent browser versions to achieve the best in interactivity and performance. Those chapters concentrate mainly on user controls, which provide an ideal environ- ment to achieve reusability while being rela- tively quick and easy to build. This chapter concentrates on an approach mentioned a few times in this book— building server controls. This is, in many ways, the ultimate technique for reusable content because it avoids the issues related to user controls that can limit their useful- ness. This chapter looks at two different server controls, both developed from user controls built in previous chapters. You’ll see how you can easily convert the MaskedEdit control into a server control—effectively a TextBox control with extra behavior added. Then this chapter looks at the SpinBox control, again taking it from the user control stage shown in Chapter 7, “Design Issues for User Controls,” to a full-fledged server control. The SpinBox control is a IN THIS CHAPTER The Advantages of Server Controls 298 The Basics of Building Server Controls 298 Building a MaskedEdit Server Control 305 BEST PRACTICE: Providing a Default Constructor for a Class 307 BEST PRACTICE: Specifying the Versions of Command- Line Tools 312 Building a SpinBox Server Control 315 Making the SpinBox Control Adaptive 335 Installing a SpinBox Control in the GAC 348 Summary 352 11 0672326744 CH08 5/4/04 12:24 PM Page 297 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... interface, user interface, and implementation should look like The Life Cycle of ASP.NET Controls When you build server controls, the life cycle (that is, the way that the controls are instantiated, the events that they react to, and the point at which they are destroyed) is relatively simple As you have seen in earlier chapters, the ASP.NET page framework creates an instance of the user 299 300 8 Building... transaction completes) useful for the common kinds of user controls you will create The Life Cycle of a Server Control An ASP.NET server control has a life cycle similar to that of user controls, which is to be expected because both types of controls inherit from the base class for all ASP.NET controls— System.Web.UI.Control The Control class handles just six events, which are shown in Table 8.1 in the... WebControl by using the statement If page and behave just like the “native” server TypeOf oCtrl Is HtmlControl controls provided with ASP.NET Creating a Class for a Server Control A server control is simply a NET Class file that is compiled into an assembly and instantiated within an ASP.NET page Depending on which base class you inherit from, you must import the namespaces that contain that base class and... MaskedEdit Server Control The MaskedEdit user control you created in Chapter 6, “Client-Side Script Integration,” is basically an ASP.NET TextBox control with extra features added These extra features consist of attributes you add to the element that ASP.NET generates for you when you use a TextBox control The following are the extra attributes and features: n A title attribute... is that you have to reference the built-in ASP.NET objects (such as Server, Request, and Session) via the static Context object For example, to URL-encode the query string for the page that creates the background image for the text box, you use Context.Server.UrlEncode(value) The other point to watch is that several namespaces are imported by default into ASP.NET pages, whereas none are imported by... It means that what you think are obvious object types and constants—ones you use in ASP.NET pages all the time—are often not available in a class file An example of this is the predefined vbCrlf constant that represents a carriage return It lives in the Microsoft.VisualBasic namespace, which is imported by default into ASP.NET pages written in Visual Basic.NET but not into a class file You therefore... what’s happening inside controls when they are instantiated and used You reference the Trace object of the hosting ASP.NET page through the static Context object and write a message to it—including the current value of the control As you’ll see later, this appears in the output generated by ASP.NET when tracing is enabled in the hosting page Saving Control Values in the Viewstate The sample control uses... override existing features that you don’t want, in order to remove them or change their behavior, and add any extra features you need n Plan where and how the control must handle the events raised by the ASP.NET page framework so that you know when and where you need to interact with the framework and the base class to create the required output in the page n Create the class file to implement the control,... you are inheriting from—in this case, Control Then, to generate the output from the control, you override the Render method of the base Control class The output you create here will be injected into the ASP.NET page that uses the control In some cases, you might need to import other namespaces as well For example, if you decide to inherit from HtmlControl or WebControl instead of Control, you must import... the final result you want Building a MaskedEdit Server Control For example, if you want to implement a control that is basically just a text box but with a few added features, you can inherit from the ASP.NET TextBox control In this case, you don’t have to do anything to implement the features that the TextBox control already provides, such as generating an element, maintaining viewstate, . samples provided with ASP. NET and is available online at www.dotnetjunkies.com/quickstart/ aspplus/doc/webctrlauthoring.aspx. 11 0672326744 CH08 5/4/04 12 :24 PM Page. example: “top =15 0,left =15 0,height=320,width=500,scrollbars=yes, resizable=no,status=no,titlebar=yes,menubar=no,location=no, fullscrceen=no,toolbar=no,directories=no” FIGURE 7 .13 The browser-adaptive dialog window sample page. FIGURE 7 .14 The nonmodal (new window) dialog page. 10 0672326744 CH07 5/4/04 12 :26 PM Page 2 91 Please

Ngày đăng: 21/01/2014, 09:20

Mục lục

  • cover.pdf

  • page_r1.pdf

  • page_r2.pdf

  • page_r3.pdf

  • page_r4.pdf

  • page_r5.pdf

  • page_r6.pdf

  • page_r7.pdf

  • page_r8.pdf

  • page_r9.pdf

  • page_r10.pdf

  • page_r11.pdf

  • page_r12.pdf

  • page_1.pdf

  • page_2.pdf

  • page_3.pdf

  • page_4.pdf

  • page_5.pdf

  • page_6.pdf

  • page_7.pdf

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

Tài liệu liên quan