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

← Prev

By using RegisterStartupScript() method of ClientScript class. Yes, you don't need to use the ScriptManage to register a JS fuction in Asp.Net. You can register and call a JavaScript function using RegisterStartupScript() and I'll show you how simple it is in C# and VB.
Here's the Script and the Markup

I have tiny little JavaScript function that takes a parameter. The function will greet the user when she/he enters the name in a textbox. So, I'll add a textbox control in the markup section.

    <form id="form1" runat="server">
            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" />--%>

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

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.

Visual Basic Code
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, which is use to register, manage add script to 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);

Happy coding.

← Previous