Register and Call JavaScript Function From Code Behind using Asp.Net - C# and Vb.Net

Often, we write programs or scripts that executes at the client side of a web application. The JavaScript is the preferred programming language for writing such scripts. However, sometimes we need to register and call these client side scripts from server side of the application. We can use Asp.Net server controls for registering Client Scripts (JavaScript Blocks) using Code Behind procedures.

Here in this article, I am going to show you how to register and call JavaScript using Code Behind procedures in Asp.Net. The article is for beginners, and I am assuming that you have basic knowledge of JavaScript Statements and Code blocks.

The examples that I am going to show you here, covers three very popular Asp.Net code behind procedures to write Client Scripts.

01) RegisterClientScriptBlock – Register a block of Script without the “<script>” tags.

02) IsStartupScriptRegistered – Returns a Boolean (true or false), when a particular start up script is registered.

03) RegisterStartupScript – Register the Client Script from Code Behind.

Note: Please do not skip the conclusion part of this article, at the end. It has an important message, related to this article.

The Script
<!DOCTYPE html>
<html>
<head>
    <title>Register and Call JavaScript From Code Behind</title>
    
    // THE SCRIPT IN THE HEAD TAG.
    <script>
        function Script_CalledFrom_CodeBehind(servertime) {
            alert('Current Server Time: ' + servertime);
        }
    </script>
</head>

<body>
    <form id="form1" runat="server">
        <div>
            <input type="button" value="Check It" onclick="startup()" />
        </div>
    </form>
</body>
</html>

The JavaScript function that we are going to register and call using code behind procedure is the one we have declared inside the <script> tag in the header section. We have named it Script_CalledFrom_CodeBehind().

In addition, I have added a Button control in the body section. The button’s click event will call another function called startup(). Look carefully inside the above markup and script. We have not declared the startup() function anywhere yet. In fact, we will register the function using code behind procedure.

Note: In fact, I am are going to call and execute two JavaScript functions. The first script is at the client side, and the other script I have registered at the server side of the application.

Code Behind (C#)
using System;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // THE FIRST JAVASCRIPT WILL BE EXECUTED ON LOAD.
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), 
                "Server Time", "javascript:Script_CalledFrom_CodeBehind('" + 
                DateTime.Now.TimeOfDay + "');", true);

            // THE SECOND JAVASCRIPT WILL BE SCRIPTED FROM CODE BEHIND AND 
                WILL BE EXECUTED ON BUTTON CLICK EVENT.
            // SO, CHECK IF THE SCRIPT HAS BEEN REGISTERED.

            if (!(Page.ClientScript.IsStartupScriptRegistered("Registered Script")))
            {
                // REGISTER THE SCRIPT.

                string sScript = "";
                sScript = sScript + "function startup() {";
                sScript = sScript + "alert('Calling another script on Button Click event." + 
                    "This script is registered at Code Behind.');";
                sScript = sScript + "}";

                // REGISTER NOW.
                Page.ClientScript.RegisterStartupScript(this.GetType(), "Registered Script", sScript, true);
            }
        }
    }
}
Vb.Net
Option Explicit On

Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles form1.Load
        If Not IsPostBack Then

            ' THE FIRST JAVASCRIPT WILL BE EXECUTED ON LOAD.
            Page.ClientScript.RegisterClientScriptBlock _
                (Me.GetType, "Server Time", "javascript:Script_CalledFrom_CodeBehind('" & TimeOfDay & "');", True)

            ' THE SECOND JAVASCRIPT WILL BE SCRIPTED FROM CODE BEHIND AND
                WILL BE EXECUTED ON BUTTON CLICK EVENT.
            ' SO, CHECK IF THE SCRIPT HAS BEEN REGISTERED.

            If Not (Page.ClientScript.IsStartupScriptRegistered("Registered Script")) Then
                ' REGISTER THE SCRIPT.

                Dim sScript As String = ""
                sScript = sScript & "function startup() {"
                sScript = sScript & "alert('Calling another script on Button Click event." & _
                    "This script is registered at Code Behind.');"
                sScript = sScript & "}"

                ' REGISTER NOW.
                Page.ClientScript.RegisterStartupScript(Me.GetType, "Registered Script", sScript, True)
            End If
        End If
    End Sub
End Class
Conclusion

Registering and calling Client Scripts, particularly JavaScript from code behind is simple. However, this feature comes with a small drawback. As you can see, the script that I have registered from code behind (Script_CalledFrom_CodeBehind()), is actually written (declared) inside the <head> tag of the page. This can sometimes slow down the page loading speed.

Please read more about Render-Blocking JavaScript in this Google's PageSpeed Insights to understand this better.

Typically, a browser will stop rendering (loading) the page (for a while) until it read and loads the script completely. This will effect the page load time, which may sometimes be very annoying for users, especially if they are using a mobile phone. Therefore, it is advisable to write the script after the <body> tag.

If you have written the scripts in a .js file and you add that file using the scripts’ src attribute in your web page, then you must use the HTML async attribute. This attribute will ensure that the file is loaded asynchronously.

Like this Article? Subscribe now, and get all the latest articles and tips, right in your inbox.

Enter your email id

Delivered by FeedBurner
Tweet this article Facebook Google+
comments powered by Disqus

Join our Google Plus Community and be a part of a discussion!