Monday, July 26, 2010

Creating client script dynamically

In many cases, you can create the client script for your page declaratively, usually as a script block. However, you can also create client script dynamically. This is useful if the script depends on information that is available only at run time. For example, you might insert client script into a page that addresses a server control whose name (ID) is not known until the application runs, or you might create script that depends on values that you get from a user.
You can create and insert client script dynamically into a rendered page by calling methods of the ClientScriptManager class, such as the following:
·         RegisterClientScriptBlock, which inserts a script block at the top of the rendered page.
·         RegisterStartupScript, which inserts a script block at the end of the rendered page.
The following example shows how to add dynamically generated client script to the page. The code checks whether a check box named 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 whose AutoPostBack property is set to true and a PlaceHolder control named PlaceHolder1.

void Page_Load(object sender, EventArgs e)
        String scriptText = "";
        scriptText += "function DisplayCharCount(){";
        scriptText += "   spanCounter.innerText = " + 
            " document.forms[0].TextBox1.value.length";
        scriptText += "}";
           "CounterScript", scriptText, true);
        TextBox1.Attributes.Add("onkeyup", "DisplayCharCount()");
        LiteralControl spanLiteral = new