RegisterStartupScript

The RegisterStartupScript method is used to render JavaScript to the client in the ASP.NET programming language. This method adds the code into the OnPreRender method, rather than into the Render method used in previous samples. This method allows every control to inform the page AbOUT the client-side script it needs to render. After the Render method is called, the page is able to render all the client-side script it collected during the OnPreRender method. If you call the client-side script registration methods in the Render method, the page has already completed a portion of its rendering before your client-side script can render itself.

Sample:

protected override void OnPreRender(EventArgs e)
{
Page.ClientScript.RegisterStartupScript( typeof(Page), “ControlFocus”, ”document.getElementById(‘“ + this.ClientID + “‘).focus();”, true);
}

In this listing, the code emits client-side script to automatically move the control focus to the TextBox control when the Web page loads. When you use the RegisterStartupScript method, notice that it now includes an overload that lets you specify if the method should render surrounding script tags. This can be handy if you are rendering more than one script to the page.

Also notice that the method requires a key parameter. This parameter is used to uniquely identify the script block; if you are registering more than one script block in the Web page, make sure that each block is supplied a unique key. You can use the IsStartupScriptRegistered method and the key to determine if a particular script block has been previously registered on the client using the RegisterStatupScript method.

Page.RegisterStartupScript Method