Using RegisterClientScriptBlock in ASP.NET

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’); }// -->
<input type="submit" name="Button1" value="Button" onclick="myalert();"
id="Button1" />

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)

One thought on “Using RegisterClientScriptBlock in ASP.NET

  1. Pingback: Using RegisterStartupScript in ASP.NET | ASP.NET 101

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>