0

i have this function :

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

i need to put it in a vb class so i can be able to use it in all my pages but i'm getting an error on "Page.ClientScript" saying that "Reference to a non-shred member requires an object reference"

How can i solve this please :)

Thank you !

4

1 回答 1

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")
于 2013-08-22T13:54:41.653 回答