The RegisterClientScriptBlock method enables you to put a JavaScript function at the top of a page. Thus, the script is in place for the startup of the page in the browser. Its use is illustrated
in the below listing.
<%@ Page Language="C#" %> <script runat="server"> protected void Page_Load(object sender, EventArgs e) { string customScript = @"function myalert() { alert(’ASP.NET 101’); }"; Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CustomScript", customScript, true); } </script><script type="text/javascript"><!--function myalert() { alert(’ASP.NET 101’); }// --></script><div><input type="submit" name="Button1" value="Button" onclick="myalert();"id="Button1" /></div>
From the above listing you can see that you create the JavaScript function myalert() as a string named customScript. Using Page.ClientScript.RegisterClientScriptBlock you then program the script to be placed on the page. The two possible constructions of the RegisterClientScriptBlock method are the following:
- RegisterClientScriptBlock (type, key, script)
- RegisterClientScriptBlock (type, key, script, script tag specification)
Pingback: Using RegisterStartupScript in ASP.NET | ASP.NET 101