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.
<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.
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".
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); }