2012-06-15 29 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

相關問題