Freigeben über


Beispiele für die Darstellung eines Serversteuerelements

Dieses Thema demonstriert anhand von zwei Beispielen für die Darstellung von Serversteuerelementen die folgenden Konzepte.

  • Das Außerkraftsetzen der Darstellungsmethode von WebControl.
  • Das Verwenden der Dienstprogrammmethoden von HtmlTextWriter.

Außerkraftsetzen der Darstellungsmethoden von "WebControl"

Das Steuerelement (MyLinkButton2) im folgenden Beispiel ist, abgesehen von den folgenden Unterschieden, mit der unter Beispiel für Postback mit clientseitigem Skript beschriebenen Verknüpfungsschaltfläche vergleichbar.

  • MyLinkButton2 ist von WebControl abgeleitet und erbt somit Stileigenschaften, deren Darstellung von WebControl implementiert wird.
  • MyLinkButton2 übergibt keinen unformatierten HTML-Code an die Write-Methode der HtmlTextWriter-Instanz. Stattdessen setzt es die AddAttributesToRender-Methode außer Kraft, um die Skriptfunktion an den Client zu übergeben, und die RenderContents-Methode wird außer Kraft gesetzt, um den Text für den Hyperlink zu übergeben.
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

Verwenden der Dienstprogrammmethoden von "HtmlTextWriter"

Das folgende Beispielsteuerelement (Rendered2) stimmt mit dem unter Vergleich von Komposition und Wiedergabe beschriebenen Steuerelement überein. Der einzige Unterschied besteht darin, dass Rendered2 Dienstprogrammmethoden von HtmlTextWriter verwendet, anstatt unformatierten HTML-Code an die Write-Methode der HtmlTextWriter-Instanz zu übergeben. Dieses Beispiel demonstriert die Verwendung der Dienstprogrammmethoden von HtmlTextWriter und zeigt darüber hinaus, wie mehrere HTML-Elemente von einem einzelnen Steuerelement ausgegeben werden. Das Beispiel greift auf die folgenden Methoden von HTMLTextWriter zurück.

  • AddAttribute
  • AddStyleAttribute
  • RenderBeginTag
  • RenderEndTag
  • Write

Darüber hinaus werden im Beispiel die HtmlTextWriterAttribute-Enumeration, die HtmlTextWriterStyle-Enumeration und die HtmlTextWriterTag-Enumeration verwendet.

Eine Anleitung zum Erstellen des Beispiels finden Sie unter Beispiele für Serversteuerelemente.

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

Siehe auch

Darstellen eines ASP.NET-Serversteuerelements