banner Hi, this is Shiva Kumar. You can call me Shiva. I'm a developer like you, with 7 Years of experience on different technologies. Earlier I used to write articles for Computers Today. Now I started this web site to help each other ( or ) atleast contribute some thing from my end. I'm always a student, if you need any articles or help which is not there in this web site, please send me a mail. I will update you as soon as I can.
Jun
18th

Detailed Tutorial of Using JavaScript with Asp.net

Author: admin | Files under Asp.net, tutorials

Introduction

ASP.NET provides a powerful server-based programming model with its postback architecture that allows performing all the work on the server. This approach ensures that your code is kept secure from prying eyes, and it sidesteps most browser-compatibility issues.

However, it also introduces some unavoidable limitations. The most significant weakness of postback architecture is its overhead. It is impossible to react to mouse movements or key presses on the server efficiently.

To overcome this weakness, developers use client-side JavaScript. This client-side script allows developers to react user events without posting back (or submitting to the server).

Using javascript in asp.net is simple and other many ways to do it, I will try explain the things by dividing the tutorial into following sections:

  • Adding java script code to the server control
  • About the ClientScriptManager Class
  • Using RegisterClientScriptBlock() Method
  • Using RegisterStartupScript() Method
  • Difference between RegisterClientScriptBlock and RegisterStartupScript
  • Using RegisterClientScriptInclude method
  • Using RegisterOnSubmitStatement() Method
  • Using JavaScript in a Separate File (.js)
  • Coding directly in HTML tab

Adding java script code to the server control

First we will go with easy approach, to add javascript code to the Server Control. In the below example, we will try to add Alert Box using the JavaScript code to the Asp.net server control as follows:

  1. private void Page_Load(object sender, System.EventArgs e)
  2. {
  3.         if(!Page.IsPostBack)
  4.         {
  5.                Button1.Attributes.Add("onclick","alert(’Hello World’)");
  6.          }
  7. }

We are adding the javascript code “alert(..)” on the onclick event of the button. For this we are using the button control attributes as shown above.

About the 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.

Following are the important things to know before we use the ClientScriptmanager class and its methods:

  • 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.
  • As said, IsClientScriptBlockRegistered() can be used for checking the 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.

  1. RegisterClientScriptBlock() Method
  2. RegisterStartupScript() Method
  3. RegisterClientScriptInclude Method
  4. RegisterOnSubmitStatement() Method

I will try to explain them below in this tutorial by taking examples along with it.

Using RegisterClientScriptBlock() Method

The RegisterClientScriptBlock() method adds the javascript code to the top of the web page and executes it when the page loads on the browser. It has two variations or we can say the RegisterClientScriptBlock() Method is overloaded as follows:

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

Let see the examples below, than you can easily identify the differences between the two overloaded functions:

  1. ClientScriptManager script = Page.ClientScript;
  2. if (!script.IsClientScriptBlockRegistered(this.GetType(), "Alert"))
  3. {
  4. script.RegisterClientScriptBlock(this.GetType(), "Alert", "alert(’hi’)",true);
  5. }

Did you observed that, we did not used the <script> tags to the javascript code “alert(‘hi’)”. That is what the last argument (addScripttags ) does so, we passed value as true. I think, now, you can imagine what the other overloaded version does:

  1. ClientScriptManager script = Page.ClientScript;
  2. if (!script.IsClientScriptBlockRegistered(this.GetType(), "Alert"))
  3. {
  4. script.RegisterClientScriptBlock(this.GetType(), "Alert",
  5. "<script type="text/javascript"><!–mce:0–></script>");
  6. }

We explicitly added the <script> tags. That is the difference between the two overloaded functions of the RegisterClientScriptBlock() method.

Using RegisterStartupScript() Method

RegisterStartupScript() Method also, injects the javascript code to the top of the web page and executes it when the page loads on the browser.Ya, it looks like RegisterStartupScript and RegisterClientScriptBlock same but, thier is a difference between them, I will try to explain the difference between these two methods in the next section. For now, we will see what are the variations or overloaded methods of the RegisterStartupScript().

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

The difference between the two overloaded is the last Boolean argument , “addScriptTags”. If it is set to true, the <script> tags are added automatically to the javascript code. (You can see the explanation for this in the above section).

Difference between RegisterClientScriptBlock and RegisterStartupScript

As i said above the RegisterClientScriptBlock and RegisterStartupScript methods adds the javascript code to the top of the web page and executes it when the page loads on the browser. So, what is the difference between them and why we have two different functions? See the below description carefully:

  • RegisterClientScriptBlock method places the JavaScript directly after the opening <form> element in the page. In this case, we will not be able to access the form elements.
  • RegisterStartupScript method places the JavaScript at the bottom of the ASP.NET page right before the closing </form> element. So, all the form elements can be easily accessed in the javascript code


Using RegisterClientScriptInclude method

Another method RegisterClientScriptInclude(), which includes the JavaScript .js file as follows:

  1. ClientScriptManager script = Page.ClientScript;
  2. if (!script.IsClientScriptBlockRegistered(this.GetType(), "ValidateJs"))
  3. {
  4. script.RegisterClientScriptInclude (this.GetType(),"ValidateJs", "validate.js");
  5. }

RegisterClientScriptInclude() method also have two variations or overloaded as follows:

  • ClientScriptManager.RegisterClientScriptInclude (String, String)
  • ClientScriptManager.RegisterClientScriptInclude (Type, String, String)

Only the difference between the two variations is Type argument.

Later, in the below section, I will show another way of adding the javascipt .js file.

Using RegisterOnSubmitStatement() Method

As the method itself says that, it executes the javascript code when the user submits the data to the server, (On submit Statement). Sometimes, we will require getting confirmation from the user before submitting the form to server. Let see this with an example, where I will use java script confirm boxes as follows:

  1. if (!script.IsClientScriptBlockRegistered(this.GetType(), "SubmitScript"))
  2. {
  3. script.RegisterOnSubmitStatement(this.GetType(), "SubmitScript",
  4. "alert(’Submit Clicked’)");
  5. }

Now, when the user clicks on the submit button , a confirmation message will come which shows the “ok” or “cancel” try clicking the “cancel” button, the form will not be submitted.

Using JavaScript in a Separate File (.js)

Most of the web pages will have length javascript code and we cannot add this script code as in the above example. The best is put all the length functions to a javascript file .js and add it to the asp.net pages as follows:

  1. if(!Page.IsPostBack)
  2. {
  3.         if(!Page.IsClientScriptBlockRegistered("MyScript"))
  4.         {
  5.                    Page.RegisterClientScriptBlock("MyScript","<script src="MyJavaScriptFile.js"><!–mce:1–></script>");
  6.        }

In this example, we use RegisterClientScriptBlock method to add the script file. Now, suppose, if you want to use one of the script functions to be invoked when the button is clicked, we can directly use it as follows:

  1.     Button1.Attributes.Add("onclick","ConfirmationWindow();");

ConfirmationWindow() function resides in the javascript file which we added above.

Coding directly in HTML tab

All the above things explained the concepts of adding the javascript code dynamically from the code behind classes. But, if you want we can directly open the HTML tab and add the JavaScript code their. Follow these steps:

  • Create a new asp.net application
  • When webform1 displayed you will see that there are two tab below Design and HTML
  • Open HTML tab and add the javascript code directly their, by using the script tags

    < Script language= “JavaScript”>

    </Script>

Note: I tried my best to put all the required things in to this tutorial. If I missing some thing please mention, it will helpful to me and others.

Similar Posts - 90% of Users have seen these posts also

Post a Comment