CODEDIGEST
Home » FAQs
Search
 

Technologies
 

How to Inject a JavaScript method from CodeBehind Class in ASP.Net?
Submitted By Satheesh Babu B
On 2/17/2009 7:53:06 AM
Tags: Interview Questions,ASP.Net,JavaScript  

How to Inject a JavaScript method from CodeBehind Class in ASP.Net?

 

.Net 2.0 introduced a new class called ClientScriptManager to do this task easily. ClientScript property of the Page object will give us an instance of ClientScriptManager object. This class uniquely identifies scripts by a key String and a Type. Scripts with the same key and type are considered duplicates and hence similar scripts are avoided.

 

The below code will explain us 2 of the useful methods of ClientScriptManager object that helps in injecting JavaScript methods.

 

ClientScriptManager.RegisterClientScriptBlock() Method

ClientScriptManager script = Page.ClientScript;
        if (!script.IsClientScriptBlockRegistered(this.GetType(), "Alert"))
        {
            script.RegisterClientScriptBlock(this.GetType(), "Alert", "<script type=text/javascript>alert('hi')</script>");
        }

 

 

ClientScriptManager.RegisterStartupScript() Method

ClientScriptManager script = Page.ClientScript;
txtName.Text = "Satheesh Babu";
        if (!script.IsStartupScriptRegistered (this.GetType(), "Alert"))
        {
            script.RegisterStartupScript (this.GetType(), "Alert", "<script type=text/javascript>alert(document.getElementById('txtName').value)</script>");
        }

Recent FAQs
  • View All FAQs..