Click here to Skip to main content
16,017,881 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)


How do I start a JavaScript function from a aspx.cs or aspx.vb program?

Default.aspx
HTML
<script type="text/javascript">
    function function1()
    {
       ...
    }
</script>


Default.aspx.vb
VB
Public Class _Default
    Inherits Page

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
         'Execute some code first
         'Then execute the javascript function
         ClientScript.RegisterClientScriptBlock(Me.GetType(), "JavaScript", "JavaScript:function1(); ", True)
    End Sub
End Class


What I have tried:

I have tried an OnClientClick in a Button or Checkbox but I want to run some code first then execute the JavaScript Function.
Posted
Updated 21-Apr-16 7:26am
v2

1 solution

You can't call js from your code-behind files as js runs in the browser after your code-behind has finished rendering the page. You can add code to the page using ClientScript.RegisterStartupScript which will do it in such a way that the js is executed when the page loads in the browser, but that's all it does, it doesn't actually execute the js there and then, nothing can do that for reasons stated above.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 21-Apr-16 21:22pm    
This is all correct, but most inquirers asking similar questions would hardly understand it. I'm not so sure that our inquirer, who formally accepted the answer, got clear understanding. Learning of some basics is required. I up-voted the answer with my 4.
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900