Esempi di esecuzione del rendering di un controllo server
In questo argomento vengono forniti due esempi di esecuzione del rendering di un controllo server che descrivono le nozioni riportate di seguito.
- Esecuzione dell'override del metodo di rendering di WebControl.
- Utilizzo dei metodi di utilità di HtmlTextWriter.
Esecuzione dell'override dei metodi di rendering di WebControl
Il controllo (MyLinkButton2
) nel seguente esempio è simile al pulsante di collegamento descritto in Esempio di postback mediante script lato client, con le differenze seguenti.
MyLinkButton2
deriva da WebControl, quindi eredita le proprietà di stile il cui rendering viene implementato da WebControl.MyLinkButton2
non passa HTML non elaborato al metodo Write dell'istanza HtmlTextWriter. Al contrario, esegue l'override del metodo AddAttributesToRender, per passare la funzione script al client, e l'override del metodo RenderContents, per passare il testo del collegamento ipertestuale.
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
Utilizzo dei metodi di utilità di HtmlTextWriter
Il seguente controllo di esempio (Rendered2
) è identico al controllo descritto in Composizione e rendering, con la differenza che Rendered2
utilizza i metodi di utilità di HtmlTextWriter invece di passare HTML non elaborato al metodo Write dell'istanza HtmlTextWriter. In questo esempio viene mostrato l'utilizzo dei metodi di utilità di HtmlTextWriter e come generare più elementi HTML da un singolo controllo. Nell'esempio vengono utilizzati i seguenti metodi di HTMLTextWriter.
- AddAttribute
- AddStyleAttribute
- RenderBeginTag
- RenderEndTag
- Write
Vengono, inoltre, utilizzate le enumerazioni HtmlTextWriterAttribute, HtmlTextWriterStyle e HtmlTextWriterTag.
Per generare l'esempio, vedere le istruzioni in Esempi di controlli server.
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