共用方式為


呈現伺服器控制項範例

這個主題將提供兩個呈現伺服器控制項的範例以說明下列的概念。

  • 覆寫 WebControl 的呈現方法。
  • 使用 HtmlTextWriter 的公用程式方法。

覆寫 WebControl 的呈現方法

下列範例中的控制項 (MyLinkButton2) 和使用用戶端指令碼回傳範例中所描述的連結按鈕類似,下列則為兩者間的差異。

  • MyLinkButton2 衍生自 WebControl 並繼承樣式屬性,樣式屬性的呈現是由 WebControl 實作。
  • MyLinkButton2 並不會將未經處理的 HTML 傳遞給 HtmlTextWriter 執行個體 (Instance) 的 Write 方法;相反地,它會覆寫 AddAttributesToRender 方法而將指令碼函式傳遞給用戶端,並覆寫 RenderContents 方法以傳遞超連結 (Hyperlink) 的文字。
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;

namespace CustomControls {
   
   public class MyLinkButton2: WebControl, IPostBackEventHandler{
      
      public MyLinkButton2() : base(HtmlTextWriterTag.A) {
      }
      
      public virtual string Text {
                  get {
                        object o = ViewState["Text"];
                        return((o == null) ? String.Empty : (string)o);
                  }
                  set {
                        ViewState["Text"] = value;
                  }
      }
      // Defines the Click event.
      //
      public event EventHandler Click;
      
      // Invokes delegates registered with the Click event.
      //
      protected virtual void OnClick(EventArgs e) {
         
         if (Click != null) {
            Click(this, e);
         } 
      }
      
      
      // Method of IPostBackEventHandler that raises change events.
      //
      public void RaisePostBackEvent(string eventArgument){
         
         OnClick(new EventArgs());
      }

      protected override void AddAttributesToRender(HtmlTextWriter writer) {
                  
                  base.AddAttributesToRender(writer);
                  writer.AddAttribute(HtmlTextWriterAttribute.Href, "javascript:" + Page.GetPostBackEventReference(this));
                        
            } 
    protected override void RenderContents(HtmlTextWriter writer) {
                        writer.Write(Text);
            }
 
   }    
}
[Visual Basic]
Option Explicit
Option Strict

Imports System
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Collections

Namespace CustomControls
   Public Class MyLinkButton2
      Inherits WebControl
      Implements IPostBackEventHandler
      
      Public Sub New()
         MyBase.New(HtmlTextWriterTag.A)
      End Sub
      
      
      Public Overridable Property Text() As String
         Get
            Dim o As Object = ViewState("Text")
            If o Is Nothing Then
               Return String.Empty
            Else
               Return CStr(o)
            End If
         End Get
         Set
            ViewState("Text") = value
         End Set
      End Property
      
      ' Defines the Click event.
      '
      Public Event Click As EventHandler
      
      ' Invokes delegates registered with the Click event.
      '
      Protected Overridable Sub OnClick(e As EventArgs)
         RaiseEvent Click(Me, e)
      End Sub
      
      ' Method of IPostBackEventHandler that raises change events.
      '
      Public Sub RaisePostBackEvent(eventArgument As String) Implements IPostBackEventHandler.RaisePostBackEvent
         OnClick(New EventArgs())
      End Sub
      
      Protected Overrides Sub AddAttributesToRender(writer As HtmlTextWriter)
         MyBase.AddAttributesToRender(writer)
         writer.AddAttribute(HtmlTextWriterAttribute.Href, "javascript:" + Page.GetPostBackEventReference(Me))
      End Sub
       
      Protected Overrides Sub RenderContents(writer As HtmlTextWriter)
         writer.Write(Text)
      End Sub
   End Class 
End Namespace

使用 HtmlTextWriter 的公用程式方法

下列的範例控制項 (Rendered2) 和撰寫和呈現的比較中所描述的控制項只有以下的不同點,即 Rendered2 使用 HtmlTextWriter 的公用程式方法將未經處理的 HTML 傳遞給 HtmlTextWriter 執行個體的 Write 方法。這個範例將說明如何使用 HtmlTextWriter 的公用程式方法,以及如何從單一控制項發出多個 HTML 項目。範例中將使用下列 HTMLTextWriter 的方法。

  • AddAttribute
  • AddStyleAttribute
  • RenderBeginTag
  • RenderEndTag
  • Write

此外,範例中也將使用 HtmlTextWriterAttributeHtmlTextWriterStyleHtmlTextWriterTag 列舉型別 (Enumeration)。

若要建置範例,請參閱伺服器控制項範例中的說明。

using System;
using System.Web;
using System.Web.UI;
using System.Collections.Specialized;

namespace CustomControls
{
   
   public class Rendered2 : Control, IPostBackDataHandler, IPostBackEventHandler
   {
   
      private String text1;
      private String text2;
      private String text = "Press button to see if you won.";
      private int number = 100;
      

      private int Sum
      {
         get 
         {     
            return Int32.Parse(text1) + 
               Int32.Parse(text2);
         } 
      }
      
      public int Number
      {
         get
         {
            return number;
         }
         set
         {
            number = value;
         }
      }
      
      
      public String Text {
         get {
            return text;
         }
         set { 
            text = value;
         }     
      }
      
      public event CheckEventHandler Check;
      
      protected virtual void OnCheck(CheckEventArgs ce)
      {
         if (Check != null)
         {
            Check(this,ce);
         }
      }
      
      public virtual bool LoadPostData(string postDataKey, 
         NameValueCollection values) {
         text1 = values[UniqueID + "t1"];
         text2 = values[UniqueID+ "t2"];
         Page.RegisterRequiresRaiseEvent(this);
         return false;
      }
      
      public virtual void RaisePostDataChangedEvent() {
      }
      
      public void RaisePostBackEvent(string eventArgument){
         
         OnCheck(new CheckEventArgs(Sum - Number));
      }
      
      protected override void Render(HtmlTextWriter writer) {
         writer.RenderBeginTag(HtmlTextWriterTag.H3); 
         writer.Write("Enter a number:"); 
      writer.RenderEndTag(); 
         
      writer.AddAttribute(HtmlTextWriterAttribute.Type,"Text");
      writer.AddAttribute(HtmlTextWriterAttribute.Name,this.UniqueID + "t1");
      writer.AddAttribute(HtmlTextWriterAttribute.Value,"0");
      writer.RenderBeginTag(HtmlTextWriterTag.Input);       
         writer.RenderEndTag(); 

         writer.RenderBeginTag(HtmlTextWriterTag.H3);  
         writer.Write("Enter another number:"); 
      writer.RenderEndTag(); 

         writer.AddAttribute(HtmlTextWriterAttribute.Type,"Text");
      writer.AddAttribute(HtmlTextWriterAttribute.Name,this.UniqueID + "t2");
      writer.AddAttribute(HtmlTextWriterAttribute.Value,"0");
      writer.RenderBeginTag(HtmlTextWriterTag.Input);       
      writer.RenderEndTag(); 
      
         writer.RenderBeginTag(HtmlTextWriterTag.Br);
      writer.RenderEndTag(); 

      writer.AddAttribute(HtmlTextWriterAttribute.Type,"Submit");
      writer.AddAttribute(HtmlTextWriterAttribute.Name,this.UniqueID);
      writer.AddAttribute(HtmlTextWriterAttribute.Value,"Submit");
      writer.AddStyleAttribute(HtmlTextWriterStyle.Height,"25 px");
      writer.AddStyleAttribute(HtmlTextWriterStyle.Width,"100 px");
      writer.RenderBeginTag(HtmlTextWriterTag.Input);    
         writer.RenderEndTag(); 
         
         writer.RenderBeginTag(HtmlTextWriterTag.Br);
         writer.RenderEndTag(); 
         
         writer.RenderBeginTag(HtmlTextWriterTag.Span); 
         writer.Write(this.Text);
         writer.RenderEndTag(); 
      }
   }     
}

// CheckEvent.cs.
// Contains the code for the custom event data class CheckEventArgs.
// Also defines the event handler for the Check event.
using System;

namespace CustomControls
{
      public class CheckEventArgs : EventArgs
      {
            private bool match = false;
            
            public CheckEventArgs (int difference)
            {
                  if (difference == 0)
                  {
                        match = true;
                  }
            }
            public bool Match
            {
                  get
                  {
                        return match;
                  }
            }
      }
      
      public delegate void CheckEventHandler(object sender, CheckEventArgs ce);
}
[Visual Basic]
Option Explicit
Option Strict

Imports System
Imports System.Web
Imports System.Web.UI
Imports System.Collections.Specialized

Namespace CustomControls
   Public Class Rendered2
      Inherits Control
      Implements IPostBackDataHandler, IPostBackEventHandler
      
      Private text1 As String
      Private text2 As String
      Private _text As String = "Press the button to see if you won."
      Private _number As Integer = 100
      
      Private ReadOnly Property Sum() As Integer
         Get
            Return Int32.Parse(text1) + Int32.Parse(text2)
         End Get
      End Property
      
      Public Property Number() As Integer
         Get
            Return _number
         End Get
         Set
            _number = value
         End Set
      End Property
      
      Public Property Text() As String
         Get
            Return _text
         End Get
         Set
            _text = value
         End Set
      End Property
      
      Public Event Check As CheckEventHandler
      
      Protected Overridable Sub OnCheck(ce As CheckEventArgs)
         RaiseEvent Check(Me, ce)
      End Sub
      
      
      Public Overridable Function LoadPostData(postDataKey As String, values As NameValueCollection) As Boolean Implements IPostBackDataHandler.LoadPostData
         text1 = values((UniqueID & "t1"))
         text2 = values((UniqueID & "t2"))
         Page.RegisterRequiresRaiseEvent(Me)
         Return False
      End Function
      
      
      Public Overridable Sub RaisePostDataChangedEvent() Implements IPostBackDataHandler.RaisePostDataChangedEvent
      End Sub
      
      
      Public Sub RaisePostBackEvent(eventArgument As String) Implements IPostBackEventHandler.RaisePostBackEvent
         OnCheck(New CheckEventArgs(Sum - Number))
      End Sub
      
      Protected Overrides Sub Render(writer As HtmlTextWriter)
         writer.RenderBeginTag(HtmlTextWriterTag.H3)
         writer.Write("Enter a number:")
         writer.RenderEndTag()
         
         writer.AddAttribute(HtmlTextWriterAttribute.Type, "Text")
         writer.AddAttribute(HtmlTextWriterAttribute.Name, Me.UniqueID + "t1")
         writer.AddAttribute(HtmlTextWriterAttribute.Value, "0")
         writer.RenderBeginTag(HtmlTextWriterTag.Input)
         writer.RenderEndTag()
         
         writer.RenderBeginTag(HtmlTextWriterTag.H3)
         writer.Write("Enter another number:")
         writer.RenderEndTag()
         
         writer.AddAttribute(HtmlTextWriterAttribute.Type, "Text")
         writer.AddAttribute(HtmlTextWriterAttribute.Name, Me.UniqueID + "t2")
         writer.AddAttribute(HtmlTextWriterAttribute.Value, "0")
         writer.RenderBeginTag(HtmlTextWriterTag.Input)
         writer.RenderEndTag()
         
         writer.RenderBeginTag(HtmlTextWriterTag.Br)
         writer.RenderEndTag()
         
         writer.AddAttribute(HtmlTextWriterAttribute.Type, "Submit")
         writer.AddAttribute(HtmlTextWriterAttribute.Name, Me.UniqueID)
         writer.AddAttribute(HtmlTextWriterAttribute.Value, "Submit")
         writer.AddStyleAttribute(HtmlTextWriterStyle.Height, "25 px")
         writer.AddStyleAttribute(HtmlTextWriterStyle.Width, "100 px")
         writer.RenderBeginTag(HtmlTextWriterTag.Input)
         writer.RenderEndTag()
         
         writer.RenderBeginTag(HtmlTextWriterTag.Br)
         writer.RenderEndTag()
         
         writer.RenderBeginTag(HtmlTextWriterTag.Span)
         writer.Write(Me.Text)
         writer.RenderEndTag()
      End Sub
   End Class
End Namespace

' CheckEvent.vb
' Contains the code for the custom event data class CheckEventArgs.
' Also defines the event handler for the Check event.
Imports System
Namespace CustomControls
   Public Class CheckEventArgs
      Inherits EventArgs
      Private _match As Boolean = False
      
      Public Sub New(difference As Integer)
         If difference = 0 Then
            _match = True
         End If
      End Sub
      
      Public ReadOnly Property Match() As Boolean
         Get
            Return _match
         End Get
      End Property
   End Class
   
   Public Delegate Sub CheckEventHandler(sender As Object, ce As CheckEventArgs)
End Namespace

請參閱

呈現 ASP.NET 伺服器控制項