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

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.

Sign up to request clarification or add additional context in comments.

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 

1 Comment

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

Your Answer

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.