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:

[title]Untitled Page[/title]
ShowValue = function()
[form id="form1" runat="server"]
[asp:TextBox ID="TextBox1" runat="server" Text="2"][/asp:TextBox]

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


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.)

Mahesh K. Sharma

No comments: