CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Multiple Ways to Call Javascript Function from CodeBehind in ASP.Net

By Satheesh Babu
Posted On Feb 02,2010
Article Rating:
Average Rating: 5
No of Ratings: 1
No of Comments: 8
Category: ASP.Net
Print this article.

Multiple Ways to Call Javascript Function from CodeBehind in ASP.Net

 

Introduction

JavaScript is one of the very versatile scripting languages that are used in Web applications. Even though we can accomplish everything in server side programming using C#, it is still advisable to do some of the things like validations, etc in clientside using JavaScript. In ASP.Net 1.x, we don’t have that much support in the framework to hook JavaScript functions from the asp.net page dynamically. This drawback was addressed with the release of ASP.Net 2.0 by providing developers a lot many features to embed JavaScript blocks dynamically through a class called ClientScriptManager.

 

ClientScriptManager Class

We normally add JavaScript functions to our webpage using <Script> tag. There are situations where we need to add the scripts dynamically from the codebehind class. In .NetFramework 1.x version, there is no class that helps us to handle this situation effectively. This drawback was addressed .NetFramework 2.0 by introducing a new class called ClientScriptManager.  This class can be used to manage and add script blocks to the asp.net page from codebehind class.

 

Things we should know about ClientScriptManager Class

Ø       ClientScript property of the Page object will give us an instance of ClientScriptManager object. We can add the scripts dynamically through this instance which will be then injected in the HTML output.

Ø       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. This will avoid the confusion caused when we are adding scripts from usercontrols. For example, the method IsClientScriptBlockRegistered() can be used for checking duplicate script registered for RegisterClientScriptBlock() method.

 

ClientScriptManager class has a set of useful methods which we can use to inject the JavaScript functions in the HTML output. We can choose to use these methods to accomplish our requirements depending on the situation.

 

Moving forward, we will discuss the usages of below 3 different methods to inject javascript from codebehind file,

1.      RegisterClientScriptBlock() Methods.

2.      RegisterStartupScript() Methods.

3.      RegisterOnSubmitStatement() Methods.

 

RegisterClientScriptBlock Methods

Page.RegisterStartUpScript() and the Page.RegisterClientScriptBlock() methods in .Netframework 1.x are now considered obsolete. These 2 methods are now packed with ClientScriptManaget class. The RegisterClientScriptBlock() method allows you to place a JavaScript function at the top of the page and gets executed on startup of the page i.e. when loading the page in the browser. There is a additional method called IsClientScriptBlockRegistered() in ClientScriptManager which will return true if a script block is already registered with  the same key, hence we can prevent the duplicate script registration.

 

There are 2 overloads for this method,

ClientScriptManager.RegisterClientScriptBlock (Type typeofscript, String key, String script)

ClientScriptManager.RegisterClientScriptBlock (Type typeofscript, String key, String script, Boolean addScriptTags)

 

Usage

Placing this code on page load or a button click makes the script to fire on the start up of subsequent postback.

 

1st overload

ClientScriptManager script = Page.ClientScript;

        if (!script.IsClientScriptBlockRegistered(this.GetType(), "Alert"))

        {

            script.RegisterClientScriptBlock(this.GetType(), "Alert", "<script type=text/javascript>alert('hi')</script>");

        }

 

2nd overload

ClientScriptManager script = Page.ClientScript;

if (!script.IsClientScriptBlockRegistered(this.GetType(), "Alert"))

        {

            script.RegisterClientScriptBlock(this.GetType(), "Alert", "alert('hi')",true);

        }

 

 

 

As I said earlier, these methods will make the script block to execute on the startup, thus we can see the alert box before the controls are actually rendered.

 

RegisterStartupScript Methods

In this section, we will see the usage ClientScriptManager.RegisterStartupScript() method of ClientScriptManager class. Both, RegisterStartupScript() methods and RegisterClientScriptBlock() methods will inject Jscript code that will fire during start up of subsequent postback. But the real difference is the former methods will inject the script after the form open tag but before page controls and the RegisterStartupScript() methods will inject the scripts after page controls but before form close tag. This indicates that injecting script using RegisterClientScriptBlock() method it is not possible to access page controls in the script block while using RegisterStartupScript() method we can.

The below markups will show a part an html output given by the asp.net page when executing these RegisterClientScriptBlock and RegisterStartupScript methods.

 

RegisterClientScriptBlock Output

    <form name="form1" method="post" action="Default.aspx" id="form1">

<div>

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJMjgzMDgzOTgzZGQfI8LfDKmcT0TXZj8jwrxqI6TOIA==" />

</div>

<script type=text/javascript>alert('hi')</script>

 

In the above html snippet, we can see the script embedded before the page controls but after form open tag.

 

RegisterStartupScript Output

<script type="text/javascript">

<!--

alert(document.getElementById('txtName').value)// -->

</script>

</form>

</body>

 In the above html snippet, we can see the script embedded after the page controls but before form close tag thus making the script able to access the page controls as I said earlier.

 

Overloads

There are 2 overloads for this method,

ClientScriptManager.RegisterClientScriptBlock (Type typeofscript, String key, String script)

ClientScriptManager.RegisterClientScriptBlock (Type typeofscript, String key, String script, Boolean addScriptTags)

 

Usage

Placing this code on page load or a button click makes the script to fire on the start up of subsequent postback. This method is also has a method called IsStartupScriptRegistered() like RegisterClientScriptBlock() methods which will check for script duplications.

 

1st overload:

ClientScriptManager script = Page.ClientScript;

txtName.Text = "Satheesh Babu";

        if (!script.IsStartupScriptRegistered (this.GetType(), "Alert"))

        {

            script.RegisterStartupScript (this.GetType(), "Alert", "&lt;script type=text/javascript&gt;alert(document.getElementById('txtName').value)&lt;/script&gt;");

        }

 

2nd overload:

ClientScriptManager script = Page.ClientScript;

txtName.Text = "Satheesh Babu";

if (!script.IsStartupScriptRegistered (this.GetType(), "Alert"))

        {

            script.RegisterStartupScript (this.GetType(), "Alert", "alert(document.getElementById('txtName').value)",true);

        }

 

When the above code is executed we will get an output like,

 

Here, the script block will get executed after the controls in the page are rendered and the controls in the page will be visible to the script as opposed to RegisterClientScriptBlock() method, refer the above figure. Thus we can access the page controls from the script block when using RegisterStartupScript() method.

 




RegisterOnSubmitStatement() Method

This section will discuss the implementation of ClientScriptManager.RegisterOnSubmitStatement() of ClientScriptManager class. Sometimes, we will require getting confirmation from the user before submitting the form to server. For example, in an input form we would like to get the confirmation from the users before storing it to the database whose validity cannot be determined through validation functions. This method can be used in such situations to provide a confirmation dialogs. This method registers scripts which will be executed at the time of submit click of a page.

 

Syntax

public void RegisterOnSubmitStatement (

    Type type,

    string key,

    string script

)

 

Usage

Placing this code on page load makes the script to fire on every submit click of the webform.

 

if (!script.IsClientScriptBlockRegistered(this.GetType(), "SubmitScript"))

        {

            script.RegisterOnSubmitStatement(this.GetType(), "SubmitScript", "alert('Submit Clicked')");

        }

 

Consider the below code,

protected void Page_Load(object sender, EventArgs e)

    {    

ClientScriptManager script = Page.ClientScript;

if (!script.IsClientScriptBlockRegistered(this.GetType(), "SubmitScript"))

     {

          script.RegisterOnSubmitStatement(this.GetType(), "SubmitScript", "return confirm('Are you sure to continue')");

     }

    }

    protected void btnSubmit_Click(object sender, EventArgs e)

    {

        Response.Write("Form is Submitted.");

    }

 

Executing the above code will bring a webform, Clicking Submit will bring a confirm box like the below figure,

 

 

Clicking Cancel will not execute the submit click event, where clicking OK will execute the event and output will be like,

 

 

Reference

ClientScriptManager Class

 

Conclusion

Thus, we have understood a subset of very useful feature given by the .Netframework 2.0 in this article. These methods will give the flexibility to handle the some of the javascript blocks to add programmatically in the HTML output based on some business requirements very easily.

Happy Coding!!

 

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
Good Article
The last part explained 'RegisterOnSubmitStatement() Method' worked for me.I added the code in Page Load event it worked.Thanks a lot....
Ask qustion
i just want to know that when i call javascript function on form for make div dynamically then div show me outside of page i want to design in a page and also want to make more then one div then what can i do.plz send on my mail ashok.vyas786@gmail.com
Calling javascript function on page load
Thanks for the code..!! It helped me a lot.
mr
Thanks

Can you complete tutorial on Javascript
Calling a JavaScript from a Page
Calling a JavaScript From MasterPage and ContentPage
Nested MAster Page
Ajax Enable Master Page
I Thhink This will be Instersting for every one
Please Thank You
Calling the Registered Script
How can I call the registered the script?
thanks
thanks a lot for this topic
thanks
:)
Nice one
This good but It was bit not readable. Check this.

http://www.devcurry.com/search?q=Execute+JavaScript+function+from+ASP.NET+codebehind

much easier.