接續上一文
step5. 覆寫 Render 方法
在 TBContextMenu 加入一個 ControlID 屬性,用來設定要呈現右鍵選單的目標控制項 ID。然後覆寫 Render 方法,來輸出相關的 JavaScript 程式碼。
Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
Dim oScript As StringBuilder
Dim sScript As String
Dim oItem As TBMenuItem
Dim bFlag As Boolean
Dim sClientID As String
Dim oControl As Control
oControl = WebFunc.FindControlEx(Me.Page, Me.ControlID)
If oControl IsNot Nothing Then
sClientID = oControl.ClientID
Else
sClientID = String.Empty
End If
oScript = New StringBuilder()
oScript.AppendLine("$(document).ready(function() {")
oScript.AppendLine("$('#" & sClientID & "').contextMenu('" & Me.ClientID & "',{")
oScript.AppendLine("bindings: {")
bFlag = False
For Each oItem In Me.Items
If StrIsNotEmpty(oItem.OnClientClick) Then
If bFlag Then
oScript.AppendLine(",")
End If
oScript.AppendLine("'" & oItem.Key & "': function(t) {")
oScript.AppendLine(oItem.OnClientClick)
oScript.AppendLine("}")
bFlag = True
End If
Next
oScript.AppendLine("}")
oScript.AppendLine("});")
oScript.AppendLine("});")
sScript = oScript.ToString
Me.Page.ClientScript.RegisterStartupScript(Me.GetType, "menu", sScript, True)
MyBase.Render(writer)
End Sub
三、測試程式
接下來要測試 TBContextMenu 控制項,首先在 HTML 碼中加入引用相關的 jqeruy.js 及 jquery.contextmenu.js。
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.contextmenu.js"></script>
在頁面放置一個 Label 及一個 TBContextMenu 控制項,TBContextMenu 的 ControlID 設定為此 Label,即在該 Label 按右鍵會出現我們設定的右鍵選單。
<asp:Label class="demo" ID="Label1" runat="server"
Text="RIGHT CLICK FOR DEMO (TBContextMenu)" Font-Bold="True"></asp:Label>
<br />
<bee:TBContextMenu ID="TBContextMenu1" runat="server" ControlID="Label1" >
<Items>
<bee:TBMenuItem Key="open" Text="Open" ImageUrl="~/image/folder.png" OnClientClick="alert('open');"/>
<bee:TBMenuItem Key="email" Text="Email" ImageUrl="~/image/email.png" OnClientClick="alert('email');" />
<bee:TBMenuItem Key="save" Text="Save" ImageUrl="~/image/disk.png" OnClientClick="alert('save');" />
<bee:TBMenuItem Key="delete" Text="Delete" ImageUrl="~/image/cross.png" OnClientClick="alert('delete');" />
</Items>
</bee:TBContextMenu>
執行程式,在 Label 上按右鍵就會出現我們在 TBContextMenu 控制項設定 Items 集合屬性的選單內容。
備註:本文同步發佈於筆者「ASP.NET 魔法學院」部落格
http://www.dotblogs.com.tw/jeff377/archive/2008/10/31/5844.aspx