2012-06-15 31 views
1

你好我正在使用这个Page.ClientScript.RegisterStartupScript()来调用背后的VB代码的JavaScript函数,这与我工作正常我的问题是我怎样才能发送变量从背后这里的JavaScript函数的代码是我到目前为止已经试过:从VB函数传递变量到客户端javascript

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) 
    Handles Me.LoadComplete 
    Dim Myname As String = "myName" 
    Dim cstype As Type = Me.GetType() 
    Page.ClientScript.RegisterStartupScript(cstype, "MyKey", "hello(Myname);", 
    True) 

End Sub 

的javascript:

<script type="text/javascript"> 
    function hello(name) { 
     alert("hello world from javascript " + name) 
    } 
</script> 

谢谢...

回答

2

你必须使用正确的报价来传递字符串:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) 
    Handles Me.LoadComplete 
    Dim Myname As String = "myName" 
    Dim cstype As Type = Me.GetType() 
    Page.ClientScript.RegisterStartupScript(cstype, "MyKey", "hello('" & Myname & "');", 
    True) 

End Sub 

注单引号括起来的变量名。

另一方式用于双向传递客户端和服务器端代码之间的数据的是隐藏的字段,例如

<asp:HiddenField ID="xhidMyname" runat="server" /> 

<input type="hidden" id="xhidMyname" runat="server" /> 

此字段将是可访问的两个客户端和服务器端通过它的“价值”属性。

+0

谢谢这个作品完美 –

1
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) 
    Handles Me.LoadComplete 
    Dim Myname As String = "myName" 
    Dim cstype As Type = Me.GetType() 
    Page.ClientScript.RegisterStartupScript(cstype, "MyKey", "hello('"&Myname&"');", 
    True) 

End Sub 
+0

没有没有工作... –

+0

雅,对不起,我错过了在字符串周围添加单引号 – Rab

相关问题