Asp.Net - How to call JavaScript function from Code behind without ScriptManager

← PrevNext →

By using the RegisterStartupScript() method of the ClientScript class, you can easily register and call a JavaScript function in ASP.NET without needing the ScriptManager. This method simplifies the process of integrating JavaScript into your ASP.NET applications. In this guide, I'll demonstrate how to use RegisterStartupScript() in both C# and VB.NET.
The Markup and the Script

I have tiny little JavaScript function that takes an argument (or parameter). The function will greet the user when she/he enter their name in a textbox. So, I'll add a textbox control in the markup section.

<body>
    <form id="form1" runat="server">
        <div>
            Enter your name: <asp:TextBox ID="tbName" runat="server"></asp:TextBox>
            <asp:Button ID="bt" runat="server" Text="Click it" OnClick="greetings" />

        <%--Or, use this button--%>
        <%--<input id="bt1" type="button" value="Click to Show time" onserverclick="greetings" runat="server" />--%>

        </div>
    </form>
</body>
<script>
    // This script will be called from code behind.
    let say_hello = (name) => {
      alert (name);
    }
</script>

It also has a button control, which when clicked will call a code behind procedure that will register and call the JS function.

Now let's call the script from code behind.

Vb.Net
Protected Sub greetings(ByVal sender As Object, ByVal e As EventArgs)
    Dim sScript As String = ""
    sScript = "window.onload = function () { say_hello('Hello " & tbName.Text & "'); }"
    Page.ClientScript.RegisterStartupScript(Me.GetType, "intro", sScript, True)
End Sub

The RegisterStartupScript() method is a member of "ClientScript" class that is used to register, manage and add script on a web page. The method takes four parameters.

1) type: The type of script to register

2) key: The unique key, which identifies the script that you have registered. Using the key you can check whether a particular script has already been registered. For example,

VB code 
If Not (Page.ClientScript.IsStartupScriptRegistered("intro")) Then ' Check if key "intro" has already been registered.
    ' If key not registered, do the following.
    ...
End If

C# code
if (!(Page.ClientScript.IsStartupScriptRegistered("intro"))) {
    // If key not registered, do the following.
    ...
}

3) script: The JS script that you will register.

4) addScriptTags: A boolean value (true or false) indicating whether to add script tags. I have set it to "true".

C# Code

protected void greetings(object sender, EventArgs e)
{
    string sScript = "";
    sScript = "window.onload = function () { say_hello('Hello " + tbName.Text + "'); }";
    Page.ClientScript.RegisterStartupScript(this.GetType(), "intro", sScript, true);
}

← PreviousNext →