使用用戶端指令碼回傳範例
下列範例建立自訂連結按鈕,透過用戶端指令碼 (JScript, JavaScript) 初始化回傳。若要建置範例,請參閱伺服器控制項範例中的說明。
如需類似這個範例,但衍生自 WebControl 的範例,請參閱呈現伺服器控制項範例。
using System;
using System.Web.UI;
using System.Collections;
namespace CustomControls {
public class MyLinkButton: Control, IPostBackEventHandler{
// 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 Render(HtmlTextWriter output) {
output.Write("<a id=\"" + this.UniqueID + "\" href=\"javascript:" + Page.GetPostBackEventReference(this) +"\">");
output.Write(" " + this.UniqueID + "</a>");
}
}
}
[Visual Basic]
Option Explicit
Option Strict
Imports System
Imports System.Web.UI
Imports System.Collections
Namespace CustomControls
Public Class MyLinkButton
Inherits Control
Implements IPostBackEventHandler
' 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 Render(output As HtmlTextWriter)
output.Write(("<a id=""" & Me.UniqueID & _
""" href=""javascript:" & _
Page.GetPostBackEventReference(Me) & """>"))
output.Write((" " & Me.UniqueID & "</a>"))
End Sub
End Class
End Namespace
在網頁上使用控制項
下列 ASP.NET 網頁使用前面範例中建立的自訂連結按鈕。
<%@ Register TagPrefix="Custom" Namespace="CustomControls" Assembly = "CustomControls" %>
<script language="C#" runat=server>
private void Button_Click(Object sender, EventArgs e) {
TextBox.BackColor = System.Drawing.Color.LightGreen;
TextBox.Text = "The link button caused postback.";
}
</script>
<html>
<body>
<form runat=server>
Here is the custom link button.<br>
<Custom:MyLinkButton Id = "Link" OnClick = "Button_Click" runat=server/>
<br><br>
<asp:TextBox id = "TextBox" Text = "Click the link" Width = "200" BackColor = "Cyan" runat=server/>
<br>
</form>
</body>
</html>
[Visual Basic]
<%@ Register TagPrefix="Custom" Namespace="CustomControls" Assembly = "CustomControls" %>
<script language="VB" runat=server>
Private Sub Button_Click(sender As Object, e As EventArgs)
TextBox.BackColor = System.Drawing.Color.LightGreen
TextBox.Text = "The link button caused postback."
End Sub
</script>
<html>
<body>
<form runat=server>
Here is the custom link button.<br>
<Custom:MyLinkButton Id = "Link" OnClick = "Button_Click" runat=server/>
<br><br>
<asp:TextBox id = "TextBox" Text = "Click the link" Width = "200" BackColor = "Cyan" runat=server/>
<br>
</form>
</body>
</html>