Professional ASP.NET 1.0 Special Edition- P33 potx

40 227 0
Professional ASP.NET 1.0 Special Edition- P33 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

 Allows expando attributes (i.e. attributes that are not pre-defined properties of the control) to be specified in a server-control declaration. Expando attributes are not interpreted and are written directly to the output HTML stream. By default, the Control class throws an exception if an attribute is not a property of the server control.  Provides consistency with the standard ASP.NET web controls since they derive from the WebControl class.  Persists the style object and any settings/state during postbacks using view state. In the control example earlier, when we used the style object, any style changes made in event handlers or in other code would not have been remembered after a postback, since the state of the style object was not being round tripped using viewstate. For our control to remember any style changes (because it is derived from Control), we'd need to implement custom statement management, by overriding the LoadViewState and SaveViewState methods. Viewstate is discussed later in the chapter. The WebControl class is designed to either assist with the rendering of a control, or take complete control of the rendering. For a simple control such as our label, the WebControl class can be used to replace most of the code we have written. To make use of the WebControl class we have to make the following changes to our code:  Derive from the WebControl class rather than Control class.  Declare a public constructor that calls the base constructor, specifying which HTML element to render.  Override the RenderContents method to emit the content we want within our <h1> element. The WebControl class takes responsibility for rendering the attributes and the begin/end-tags, so we remove the Render method.  Remove all of the style properties we implemented earlier, since the WebControl will automatically have implemented them for us. After making these changes, our C# control code looks like this: using System; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WroxControls { public class MyLabel : WebControl { string _text; public MyLabel() : base ("H1") { } public string Text { get{ return _text; } set{ _text = value; } } protected override void OnInit(EventArgs e) { base.OnInit(e); if ( _text == null) _text = "Here is some default text"; } protected override void RenderContents(HtmlTextWriter writer) { writer.Write( _text); } } }; The same control in VB.NET is shown here: Imports System Imports System.Web Imports System.Web.UI Imports System.Web.UI.WebControls Namespace WroxControls Public Class MyLabel Inherits WebControl Private _text As String Public Sub New() MyBase.New("H1") End Sub 'New Public Property Text As String Get Return _text End Get Set _text = value End Set End Property Protected Overrides Sub OnInit(e As EventArgs) MyBase.OnInit(e) If _text Is Nothing Then _text = "Here is some default text" End If End Sub Protected Overrides Sub RenderContents(writer As HtmlTextWriter) writer.Write(_text) End Sub End Class End Namespace With these changes, we need to change our ASP.NET page since the available properties names for our control have changed. You can use the WebControl class documentation to get a list of all the available properties. Here is our updated page, which now uses properties consistent with all the server controls provided as part of ASP.NET, which were discussed in Chapter 5: <%@ Register TagPrefix="Wrox" Namespace="WroxControls" Assembly="MyLabel" %> <html> <body> <Wrox:MyLabel runat="server" ForeColor="Yellow" BackColor="Black" Font-Size="36" Text="Web Controls" /> </body> </html> For controls that only require one HTML root element to be rendered, our updated control code provides a good model to follow when building server controls. Your server controls should always derive from the WebControl class unless they do not render any UI, in which case the services provided by WebControl do not provide any benefit. You can use all the other techniques we've used to render HTML so far with server controls derived from WebControl, the only difference is that your code is moved to the RenderContents method. In this revised code demonstrating the use of WebControl, I have removed support for the RepeatCount property, since that would require one or more HTML elements to be rendered at the root level (you can have any number of controls within the root element). This is something a basic web control can do. If you need to do this, you have to override the Render method. To implement the RepeatCount property in our implementation, the overridden Render method calls the base implementation of Render a number of times. The following code just calls the base Render method 3 times to demonstrate the technique: C# protected override void Render(HtmlTextWriter writer) { for(int i=0; i < 3; i++ ) { base.Render( writer ); } } VB.NET Protected Overrides Sub Render(writer As HtmlTextWriter) Dim i As Integer For i = 0 To 2 MyBase.Render(writer) Next i End Sub 'Render As expected, the control will render the label three times: To show that our server control can also be programmatically manipulated, just like any other ASP.NET server control provided out of the box, the following ASP.NET page sets all the properties of our server-control properties within the Page_Init event: <%@ Register TagPrefix="Wrox" Namespace="WroxControls" Assembly="MyLabel" %> <%@ Import Namespace="System.Drawing" %> <script runat="server" language="C#"> void Page_Init( object sender, EventArgs e ) { ourLabel.Text = "Web Controls"; ourLabel.ForeColor = Color.Yellow; ourLabel.BackColor = Color.Black; ourLabel.Font.Size = 36; } </script> <html> <body> <Wrox:MyLabel runat="server" id="ourLabel" /> </body> </html> Now that we've created a couple of server controls that generate their UI by emitting HTML, let's take a look at composite controls. These controls render their UI by reusing other server controls. An ASP.NET page is a good example of a composite control - so let's take a look at how they work in detail. Composite Controls All ASP.NET dynamic pages are created by the ASP.NET run-time using ASP.NET controls. Although you may not have realized it, we have already built several ASP.NET controls in the earlier chapters of this book just by creating ASP.NET pages and user controls. The ASP.NET page framework automatically converts and compiles pages into server controls contained within a dynamically created assembly the first time a page is requested: This server control is then used to render the page. Subsequently, when a page is requested, the precompiled server control can just be instantiated and called, resulting in great performance: The assemblies created for ASP.NET pages are automatically managed for you. If you search around your Windows system directory, you'll find a directory called Temporary ASP.NET Files. Within this you'll find sub-directories for the various web sites on your machine, which in turn will contain the assemblies for ASP.NET pages. If we open up one of these generated assemblies using the ILDASM tool, we'll see that they typically contain a single class with the same name as the ASP.NET page. This class extends (derives from) the class System.Web.UI.Page: (see the sixth item from the root in the tree control.) [...]... Control that Raises Events ASP.NET provides a powerful server-side event model As a page is being created, server controls can fire events that are caused either by aspects of a client-side postback, or by controls responding to page code that is calling their methods or changing properties These events can be captured in an ASP.NET page, or can be caught by other server controls ASP.NET server controls... such as support for loading user controls (.ascx) or templates UserControl - base class from which all user controls derive Page - base class from which all dynamically compiled ASP.NET pages derive The actual code generated by ASP.NET for these dynamically generated classes is not that different from the code we have just written for our label control One key difference is that it uses control composition... created once If the ChildControlsCreated property is set to false in your code, all child controls are released automatically Subsequently, CreateChildControls may be called again ASP.NET Pages and Composite Controls An ASP.NET page is essentially compiled into a composite control Consider this simple page: Name: ... render this using the HtmlTextWriter or by creating lots of LiteralContent objects, but it makes a lot more sense to use the high-level ASP.NET web controls we have seen in earlier chapters of this book Although we have typically only made references to these controls in ASP.NET pages before, creating these controls dynamically within a control is straightforward: using System; using System.Web; using... /> You'll notice within this HTML that each of the input elements has a name attribute By default, these ids are assigned sequentially by ASP.NET as the child controls are created and added to our control When a postback occurs, ASP.NET uses these ids to automatically push postback data into server controls that are created with the same id This automatic management of postback data... This diagram shows the main ASP.NET control classes and their inheritance hierarchy: Here is a brief description of the role of each of these classes: Control - provides a common base class for all other control types WebControl - provides methods and properties for dealing with the style This class is the base class for all ASP web controls These are always declared in an ASP.NET page using an ASP:... in place, entering a value of 'Events in ASP.NET' in our textbox and calling the Postback button will cause a message to appear below the postback button: The following code shows how to implement a server-side control that supports events in VB: Imports System Imports System.Web Imports System.Web.UI Imports System.Web.UI.WebControls Imports System.Collections.Specialized Namespace WroxControls Public... Assembly="MyFirstControl" %> Some Text The ASP.NET page parser automatically creates a LiteralControl for each block of text or significant whitespace The control would actually render the button and the literal text, since the default Render... : Control, INamingContainer { Table _table; // Make table a member so we can access it at any point protected override void CreateChildControls() { LiteralControl text; text = new LiteralControl( "ASP.NET Control Development in C#"); Controls.Add(text); TableRow row; TableCell cell; // Create a table and set a 2-pixel border _table = new Table(); _table.BorderWidth = 2; Controls.Add(_table);... needed within the td elements: ASP.NET Control Development in C# . An ASP. NET page is a good example of a composite control - so let's take a look at how they work in detail. Composite Controls All ASP. NET dynamic pages are created by the ASP. NET. run-time using ASP. NET controls. Although you may not have realized it, we have already built several ASP. NET controls in the earlier chapters of this book just by creating ASP. NET pages and. Table(); _table.BorderWidth = 2; Controls.Add(_table); // Add 10 rows each with 5 cells for(int x = 0; x < 10 ; x++) { // Create a row and add it to the table row = new TableRow();

Ngày đăng: 03/07/2014, 07:20

Từ khóa liên quan

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

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

Tài liệu liên quan