1

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 ...

asked Jun 15, 2012 at 12:48

2 Answers 2

3

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.

answered Jun 15, 2012 at 13:24

Comments

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 
answered Jun 15, 2012 at 12:52

1 Comment

ya, sorry I missed to add single quote around the string

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.