Insert (inject) client script into page in ASP.NET 2.0

November 28, 2007

Insert  (add) javaScript to code behind page as RegisterClientScriptBlock in ASP.NET 2.0

Some time we need to implement client-side functionality to page. To add that client-side functionality to page we need to add (insert) JavaScript (client-side script) into page.

For example if some user is ideal for certain time of period we should pop-up an alert window asking if user would like to continue.

You can insert strings of client side script into application or in some cases you can have separate file (include file). We will discuss both scenarios in our example.

The parameters of RegisterClientScriptBlock are:

1.       Type: The type of calling page.

2.       Key: The key to identify the script.

3.       Script: Content of the script to be sent to the client side.

4.       AddScript: Indicate whether the script should be enclosed within a <script> bloc.

Main.aspx -

<body>   
<form id=”form1″ runat=”server”>
    <div>       
      
<asp:Button ID=”Button1″ runat=”server” OnClick=”Button1_Click” Text=”Call Client Script” />
    </
div>
   
</form>
</body>

Main.aspx.cs

public partial class Main: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{  
if (!Page.IsPostBack)
    
{
       
string script = “<script> alert(‘current date and time is: “ + DateTime.Now + “‘)</script>”;
       this.Page.ClientScript.RegisterClientScriptBlock(typeof(Page), “MyKey”, script);     
}
  
}
// using external client-side file  
protected void Button1_Click(object sender, EventArgs e)
   
{
    
string scriptUrl = “include.js”;
this.Page.ClientScript.RegisterClientScriptInclude(typeof(Page), “MyKey”, scriptUrl);
}
}

Include.js
alert(“Hello from Javascript”);

When converting from .net 1.1 to 2.0 you get following warning:

‘System.Web.UI.Page.RegisterClientScriptBlock(string, string)’ is obsolete: ‘The recommended alternative is ClientScript.RegisterClientScriptBlock(Type type, string key, string script). http://go.microsoft.com/fwlink/?linkid=14202

To resolve this issue use

Page.ClientScript.RegisterClientScriptBlock(typeof(Page), “MyKey”, script);

-          Harpreet Virk