How to: Add Client Script Dynamically to ASP.NET Web Pages

Using server code, you can add client script to a page. Creating client script in server code is useful when the contents of the client script depend on information that is not available until run time. Adding client script to the page dynamically is also useful when you want the client script to execute in the following situations:

To add client script to an ASP.NET Web page dynamically

  • In server code, call one of the methods listed in the following table.

    Method

    Description

    RegisterClientScriptBlock

    Adds a script block to the top of the page. You create the script as a string, and then pass it to the method, which adds it to the page. You can use this method to insert any script into the page. Note that the script might be rendered into the page before all the elements are finished; therefore, you might not be able to reference all the elements on the page from the script.

    RegisterClientScriptInclude

    Similar to the RegisterClientScriptBlock method, but adds a script block that references an external .js file. The include file is added before any other dynamically added script; therefore, you might not be able to reference some elements on the page.

    RegisterStartupScript

    Adds a script block into the page that executes when the page finishes loading but before the page's onload event is raised. The script is typically not created as an event handler or function; it generally includes only the statements you want to execute once.

    RegisterOnSubmitStatement

    Adds script that executes in response to the page's onsubmit event. The script is executed before the page is submitted, and gives you an opportunity to cancel the submission.

    The following code example shows how to add client script to a page that executes when the user clicks a button. The button has an ID of ConfirmSubmit and posts the page back to the server. The client script displays a pop-up window requesting the user to confirm the postback.

    Protected Sub Page_Load(ByVal sender As Object, _
            ByVal e As System.EventArgs)
        Dim scriptText As String
        scriptText = "return confirm('Do you want to submit the page?')"
        ClientScript.RegisterOnSubmitStatement(Me.GetType(), _
            "ConfirmSubmit", scriptText)
    End Sub
    
    protected void Page_Load(Object sender, EventArgs e)
    {
        String scriptText = 
            "return confirm('Do you want to submit the page?')";
        ClientScript.RegisterOnSubmitStatement(this.GetType(), 
            "ConfirmSubmit", scriptText);
    }
    

    The following code example shows how to add dynamically generated client code to the page. The code checks whether a check box that has an ID of checkDisplayCount is selected. If so, the code performs the following tasks:

    • It creates a client script function that uses a span element to display the character count in a TextBox control named TextBox1.

    • It adds a client event to the TextBox control.

    • It generates the span element.

    The code assumes that the page contains a check box named checkDisplayCount with its AutoPostBack property set to true and a PlaceHolder control named PlaceHolder1.

    Protected Sub Page_Load(ByVal sender As Object, _
            ByVal e As System.EventArgs)
        If checkDisplayCount.Checked Then
            Dim scriptText As String = ""
            scriptText &= "function DisplayCharCount(){"
            scriptText &= "   spanCounter.innerText = " & _
                "document.forms[0].TextBox1.value.length"
            scriptText &= "}"
            ClientScript.RegisterClientScriptBlock(Me.GetType(), _
                "CounterScript", scriptText, True)
            TextBox1.Attributes.Add("onkeyup", "DisplayCharCount()")
            Dim spanLiteral As New LiteralControl()
            spanLiteral.Text = "<span id=""spanCounter""></span>"
            PlaceHolder1.Controls.Add(spanLiteral)
        End If
    End Sub
    
    void Page_Load(object sender, EventArgs e)
    {
        if(checkDisplayCount.Checked)
        {
            String scriptText = "";
            scriptText += "function DisplayCharCount(){";
            scriptText += "   spanCounter.innerText = " + 
                " document.forms[0].TextBox1.value.length";
            scriptText += "}";
            ClientScript.RegisterClientScriptBlock(this.GetType(), 
               "CounterScript", scriptText, true);
            TextBox1.Attributes.Add("onkeyup", "DisplayCharCount()");
            LiteralControl spanLiteral = new 
                LiteralControl("<span id=\"spanCounter\"></span>");
            PlaceHolder1.Controls.Add(spanLiteral);
        }
    }
    

See Also

Tasks

How to: Add Client Script Events to ASP.NET Web Server Controls

Concepts

ASP.NET Client Script

Client Script in ASP.NET Web Pages

Implementing Client Callbacks Programmatically Without Postbacks in ASP.NET Web Pages

Script Exploits Overview