hello i am using this Page.ClientScript.RegisterStartupScript() to call a javascript function from vb code behind , and this works fine with me My question is how can i send variables from the code behind to the javascript function here is what i have tried so far :
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>
Thank you ...
2 Answers 2
You have to use correct quotations to pass strings:
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
Note single quotes around variable name.
Another way for bi-directional passing of data between client and server-side code is hidden fields, e.g
<asp:HiddenField ID="xhidMyname" runat="server" />
or
<input type="hidden" id="xhidMyname" runat="server" />
This field will be accessible both client-side and server side via it's "value" property.
Comments
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