Click here to Skip to main content
15,348,965 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Is it possible to to call a javascript function from code behind?

What I have tried:

All the suggested answers from other threads, which run the code on page load, which is not what I am looking for.


<pre>Public Class home
    Inherits Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        pageTitle.Text = "Builder" & System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()

        Dim Script As ClientScriptManager = Page.ClientScript

        If Not Script.IsClientScriptBlockRegistered(Me.[GetType](), "Alert") Then
            Script.RegisterClientScriptBlock(Me.[GetType](), "Alert", "<script type=text/javascript>alert('hi')</script>")
        End If

    End Sub

End Class
Updated 4-Mar-21 22:43pm

1 solution

You can't call javascript from your code behind. Think about the lifecycle of your code;

1 User requests a url
2 Your c# runs on the server and generates a stream of html to return to the client
3 The c# code finishes and the resulting html that was generated is sent to the client
4 The client browser interprets the html for visual display and interprets and runs any javascript

When your c# code is running there is nothing to interpret or execute javascript as the client browser has not received any output from your page. Your c# runs in its entirety on the server and then the javascript runs in its entirety on the client. You can't have them running at the same time as the web just doesn't work like that.

All RegisterClientScriptBlock is doing is injecting js into the html waiting to be sent to the browser so that it is executed when the browser receives it, which is step 4 which is after your c# has finished running.
Member 14476420 8-Oct-19 8:30am
Thank you for clarifying this. Much appreciated

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