Friday, December 17, 2010

When to Use RegisterStartupScript & RegisterClientScriptBlock in code.

Assume you have a control named "TextBox1" in aspx file, and its value is "2"
also, you have a javascript function called "ShowValue" which will alert the value of TextBox1.
so, your aspx file like this:
Code:

[title]Untitled Page[/title]
[script]
ShowValue = function()
{
alert(document.getElementById("TextBox1").value);
}
[/script]
[/head]
[body]
[form id="form1" runat="server"]
[div]
[asp:TextBox ID="TextBox1" runat="server" Text="2"][/asp:TextBox]
[/div]
[/form]
[/body]
[/html]

now, in server-side, at Page_Load method, you set value of "TextBox1" to "9" and call "ShowValue" from server.

Code:

TextBox1.Text = "9";
Page.ClientScript.RegisterStartupScript(Type.GetType("System.String"), "addScript", "ShowValue()", true);

that is.

The RegisterClientScriptBlock method adds a script block to the top of the rendered page.

while, the script block added by the RegisterStartupScript method executes when the page finishes loading but before the page's OnLoad event is raised.
(it means the RegisterStartupScript method adds a script block to the end of the rendered page.)

Thanks
Mahesh K. Sharma

No comments: