Using JavaScript Effectively in ASP.NET 2.0 - Part 1
 
Published: 17 Sep 2008
Abstract
The .NET Framework 2.0 introduced many new feature that make JavaScript usage with ASP.NET pages easy. The ClientScriptManager class in the framework has many new useful methods that help developers use these features very effectively. In this first part of the series, Satheesh discusses some of the common scenarios to use the frequently used overload methods of the ClientScriptManager class. He starts with an overview of the ClientScriptManager class and then examines the RegisterClientScriptBlock, RegisterStartupScript, and RegisterOnSubmitStatement methods with the help of relevant source code, screenshots and usage instructions.
by Satheesh Babu
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 37507/ 89

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#, we can still prefer to do some of the things, like validations, etc., using JavaScript. In ASP.NET 1.x, we do not 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 of features to embed JavaScript blocks dynamically through a class called ClientScriptManager. I have divided this article into 2 parts. Part 1 will deal with 3 different methods that are packed with ClientScriptManager class with examples, while the Part 2 will discuss the left out methods with some other useful JavaScript tips for ASP.NET.

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 .NET Framework 1.x version, there is no class that helps us to handle this situation effectively. This drawback was addressed in .NET Framework 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 be 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 similar scripts are then avoided. This will avoid the confusion caused when we are adding scripts from user controls. For example, the method IsClientScriptBlockRegistered() can be used for checking duplicate scripts 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.

This part of the article will discuss the usages of 3 different methods.

1.    RegisterClientScriptBlock() Method

2.    RegisterStartupScript() Method

3.    RegisterOnSubmitStatement() Method

RegisterClientScriptBlock() Methods

Page.RegisterStartUpScript() and the Page.RegisterClientScriptBlock() methods in .NET Framework 1.x are now considered obsolete. These two methods are now packed with ClientScriptManaget class. The RegisterClientScriptBlock() method allows you to place a JavaScript function at the top of the page and it gets executed on startup of the page (when loading the page in the browser). There is an 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.

Listing 1 - RegisterClientScriptBlock Overloads

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.

Listing 2 - 1st overload

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

Listing 3 - 2nd overload

ClientScriptManager script = Page.ClientScript;
if (!script.IsClientScriptBlockRegistered(this.GetType(), "Alert"))
{
script.RegisterClientScriptBlock(this.GetType(), "Alert""alert('hi')",true);
}

Figure 1 - RegisterClientScriptBlock Output

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() method and RegisterClientScriptBlock() method 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. However, using RegisterStartupScript() method we can.

The markups below (Listing 4 and 5) will show a part html output given by the asp.net page when executing these RegisterClientScriptBlock and RegisterStartupScript methods.

Listing 4 - 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.

Listing 5 - RegisterStartupScript Output

<script type="text/javascript">
<!--
alert(document.getElementById('txtName').value)// -->
</script>
</form>
</body>

In the above html snippet (Listing 5), 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.

Listing 6 - RegisterClientScriptBlock Overloads

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 fire on the start up of subsequent postback. This method also has a method called IsStartupScriptRegistered(), like RegisterClientScriptBlock() methods, which will check for script duplications. Refer to the code below for the implementation of the RegisterClientScriptBlock() method.

Listing 7 - 1st overload

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

Listing 8 - 2nd overload

ClientScriptManager script = Page.ClientScript;
txtName.Text = "Welcome to AspAlliance!!!";
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 similar to "Figure 2 - RegisterStartupScript Output."

Figure 2 - RegisterStartupScript Output

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 to 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 confirmation dialogs. This method registers scripts which will be executed at the time of submit click of a page.

Listing 9 - Syntax

public void RegisterOnSubmitStatement (
    Type type,
    string key,
    string script
)

Usage

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

Listing 10 - RegisterOnSubmitStatement

if (!script.IsClientScriptBlockRegistered(this.GetType(), "SubmitScript"))
{
script.RegisterOnSubmitStatement(this.GetType(), "SubmitScript""alert('Submit Clicked')");
} 

Consider the code below.

Listing 10 - RegisterOnSubmitStatement Example

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 following figure.

Figure 3 - RegisterOnSubmitStatement Output 1

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

Figure 4 - RegisterOnSubmitStatement Output 2

Conclusion

Thus, we have understood a subset of very useful feature given by the .NET Framework 2.0 in this article. These methods will give the flexibility to handle some of the JavaScript blocks and to very easily add programmatically in the HTML output based on some business requirements. Download the source code attached with this article in the download section to see it in action. Part 2 will discuss the other methods of ClientScriptManager class with some additional JavaScript tips.

Happy Coding!!

References

ClientScriptManager Class

Downloads

[Download Source]



User Comments

Title: Easy to udersatnd   
Name: Raj kumar
Date: 2011-01-18 5:58:27 AM
Comment:
This the example that how we can add additionl attribute on any asp:.. control .
First we register ClientSide Script at the time of page_load then it works.
code is all-ready given there.
ok by
Title: Javascript   
Name: mohamed
Date: 2010-11-24 8:11:08 AM
Comment:
There is a problem in the stress at which any request for the page, there will be an invitation to the confirmation message that you need to be placed in the confirmation message within the event of a button, instead of the event page, although the occurrence of this call is also a confirmation message. What is the solution
Title: Javascript   
Name: mohamed
Date: 2010-11-24 7:58:03 AM
Comment:
There is a problem in the stress at which any request for the page will be a caller confirmation message
Title: Javascript   
Name: Praveen
Date: 2010-03-10 1:59:54 AM
Comment:
Simple examples to understand the concepts.Excellent
Title: JavaScript on form load   
Name: yc
Date: 2009-05-11 4:54:00 AM
Comment:
Thanks sir,
JavaScript on form load.
That's what I was googling for 2 days.
Regards
Title: Listing6 problem   
Name: O M
Date: 2009-04-23 6:02:23 PM
Comment:
Looks like Listing6 should be for "RegisterStartupScript Output" instead it is same as Listing1.
Title: Web Developer   
Name: Dhananjay
Date: 2009-04-13 7:56:31 AM
Comment:
This is very good article.
but I have question regarding - RegisterOnSubmitStatement.
On my page there are two buttons first one is Show - to display data and another is Delete - to delete data.

In this condition using your code How can I show confirm box on only on delete button.
Title: Web Developer   
Name: Shilpa
Date: 2009-04-07 6:09:04 AM
Comment:
Javascript functionality explained in such a simple technical terms. Its wonderful.
Satish Babu, keep it up.
Title: web developer   
Name: xiaohong
Date: 2009-04-06 2:56:36 PM
Comment:
nice organized article, thanks!
Title: Dan   
Name: Dan
Date: 2009-04-01 10:00:10 AM
Comment:
I didn't know about the onsubmitscript. Thanks's
Title: Nice article   
Name: Anas
Date: 2009-04-01 3:42:09 AM
Comment:
Nice article thanks
i like it
Title: Part 2   
Name: Joe
Date: 2009-03-25 12:20:57 PM
Comment:
You can read the 2nd part here,
http://www.codedigest.com/Articles/ASPNET/221_Using_JavaScript_Effectively_in_ASPNet_20_%e2%80%93_PART_2.aspx
Title: Can you provide Part 2 Article for the same   
Name: Sree
Date: 2009-01-08 7:14:12 AM
Comment:
Hi,
Nice article ragarding clientscriptmanager class.
It would be great if you provide Part 2 continuation link for the same.
Title: Good Article   
Name: greeny
Date: 2008-12-20 2:52:31 AM
Comment:
Hi,

good to see easily understandable article.
Title: Great Article   
Name: J
Date: 2008-12-09 5:46:12 AM
Comment:
This was the first article I read on RegisterStartupScript.
Very easy to understand article with nice examples.
Thanks a lot for shairing this
Title: Programmer   
Name: Tonci Korsano
Date: 2008-09-30 2:38:46 PM
Comment:
Hi,

I think this is a good article. RegisterOnSubmitStatement() Method was explained in a simple way. I might have to use this method. However, I have read that in these methods it is more efficient to use typeOf(this) or typeOf(Page) instead of this.getType() or Page.getType()

Tonci.
Title: RE: how to execute onsumit in between the server code   
Name: Mikalai
Date: 2008-09-26 10:51:03 AM
Comment:
To Nonu:
do not be confused with server and client side code. alert could be only displayed when server side code is finished and result html is sent to the client.
Title: how to execute onsumit in between the server code   
Name: Nonu
Date: 2008-09-25 11:06:28 AM
Comment:
Hi
Your article is helped me a lot to understand clientscript class.
but i want to execute a alert in between the server side code.
Title: Good Article   
Name: Joe
Date: 2008-09-17 11:47:12 PM
Comment:
Satheesh,
Your article is really good! It is really useful to people like me!
Thanks again!
Title: Mr.   
Name: kmanral
Date: 2008-09-17 2:52:58 PM
Comment:
only useful part of article is the link to MSDN. oops...

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2020 ASPAlliance.com  |  Page Processed at 2020-09-23 5:12:41 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search