2013-08-22 77 views
0

我有這樣的功能:JavaScript提醒在Vb.net類

Public Sub javaMsg(ByVal message As String) 
    Dim sb As New System.Text.StringBuilder() 

    sb.Append("<script type = 'text/javascript'>") 

    sb.Append("window.onload=function(){") 

    sb.Append("alert('") 

    sb.Append(message) 

    sb.Append("')};") 

    sb.Append("</script>") 

    Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "alert", sb.ToString()) 
End Sub 

我需要把它放在一個VB類,所以我可以能夠在我所有的網頁使用它,但我得到的錯誤的「Page.ClientScript」的說法,「引用非粉碎成員需要一個對象引用」

我怎樣才能解決這個請:)

謝謝!

回答

2

你總是可以改變它;

Public Function javaMsg(ByVal message As String) As String 

    Dim sb As New System.Text.StringBuilder() 
    sb.Append("window.onload=function(){") 
    sb.Append("alert('") 
    sb.Append(message) 
    sb.Append("')};") 

    return sb.ToString() 

End Sub 

然後在你的頁面調用;

Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "alert", javaMsg("Hello World"), true) 

注意到有一個重載的RegisterClientScriptBlock這實際上使得腳本塊給你。

這樣,你的功能可以在你想要的任何類中,不會中斷。

或者,您可以將當前頁面作爲參考傳遞給您的方法;

Public Sub javaMsg(ByRef page As System.Web.UI.Page, ByVal message As String) 

    Dim sb As New System.Text.StringBuilder() 
    sb.Append("window.onload=function(){") 
    sb.Append("alert('") 
    sb.Append(message) 
    sb.Append("')};") 

    page.ClientScript.RegisterClientScriptBlock(page.GetType(), "alert", sb.ToString(), true) 

End Sub 

並在您的頁面調用;

'' C# does not allow you to pass the page as a Reference type. Not sure if VB.Net does or not 
'' So creating a reference to it before passing it in 
Dim refPage As System.Web.UI.Page = me.Page 
ClassName.javaMsg(refPage, "Hello World")