HOME RESOURCES PLACEMENTS CONTACT FEEDBACK SUBSCRIBE
QUICK LINKS .NET Articles
.NET Training Tutorial
HR Interview Questions
.NET Interview Questions
SQL Interview Questions
JAVA Interview Questions

Using Javascript with ASP.NET 2.0 Web Pages and Controls on the page
Javascript enables us to perform actions without posting back to the web server. There are different ways to inject javascript into the controls which can be executed on the client when the page is rendered. This article illustrate all the different possible ways.

Adding JavaScript to an HTML Server Control:
It is quite easy to add JavaScript to an HTML server control that is present on an ASP.NET page. Let's take a look at the button server control as an example. If you drag and drop an HTML Button  server control (HtmlInputButton Class) onto a page it should have the following HTML mark up on the aspx page
<input id="Button1" type="button" value="button" runat="server" />

Now add the following code in the aspx page
<html  >
<head>
    <title>PRAGIM Technologies</title>
</head>
<body onload="javascript:document.forms[0]['Button1'].value=Date();">
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Button"/>
    </div>
    </form>
</body>
</html>

If you observe the above code in bold letters, we are assigning the button vale to the Date that is retrieved using the Javascript. This Javascript code gets executed on the client and displays the current date on the client who is accessing the page as shown in the figure below.

Adding JavaScript to a Web Server Control from the code behind file:
After you drag and drop a web server control button on a web form we will have the following mark up on the aspx page
<asp:Button id="Button1" runat="server" text="Pragim"></asp:Button>

Every web server control has a property called attributes to which we can assign javascript as shown in the below code snippet. We do this in the page load event. The Add() method takes two parameters "key" and "value". The "key" property has to be the client side event name of the control to which we want to bind the javascript.
protected void Page_Load(object sender, EventArgs e)
{
        Button1.Attributes.Add("onclick", "Javascript:alert(Date());");
}
 
Changing the image displayed by an Image Button using Javascript. Performing a Simple Button-Rollover:
Lets day an Image Button in ASP.NET is displaying a "Red Colored Image" and I want to change the Image to a Green Color Image when I move the mouse over the button. This can be very easily achieved. When we drag and drop an ASP.NET image, we will have the following HTML mark up in the aspx.
<asp:ImageButton id="ImageButton1" runat="server" ImageUrl="RedButton.gif"></asp:ImageButton>

Add the following code to the defult code that is generated by the designer. We are setting the src of the image to GreenButton.gif when we move the mouse over the button and when we move the pointer awaya from the button we are setting the image to the GreenButton.gif. For this purpose we are using the onmouseover and onmouseout client side events.
<asp:ImageButton id="ImageButton1"
        onmouseover="this.src='GreenButton.gif'" 
        onmouseout="this.src='RedButton.gif'" runat="server"
        ImageUrl="button1.gif"></asp:ImageButton>

Move the mouse onto the button to check how the Image Button changes
Setting the focus of the cursor into a specific control on the webform:
For example when you type WWW.Google.com in the browser window, the google page loads and you have the cursor in the search textbox and you can start typing right awaya.

ASP.NET 2.0 makes this task much easier with the addition of the Focus() method. Now you can accomplish a focus to a TextBox control as shown here:

protected void Page_Load(object sender, EventArgs e)
{
   TextBox1.Focus(); 
}

When the page using this method is loaded in the browser, the cursor is already placed inside of the text box, ready for you to start typing. There's no need to move your mouse to get the cursor in place so you can start entering information in the form. The Focus() method will do the trick.
Calling JavaScript functions using Page.ClientScript.RegisterStartupScript() Method:
Example : Lets say we have a button on an ASP.NET page. When I click the button I want to call a Javascript function. The ID of the button is "Button1". Add the following code in your page load event of the page. We use Page.ClientScript.RegisterStartupScript() method to register the javascript when the page is loaded. We can achieve the same functionality using Page.ClientScript.RegisterClientScriptBlock() also.
protected void Page_Load(object sender, EventArgs e)
{
    Page.ClientScript.RegisterStartupScript(this.GetType(), "MyScript","function AlertPragim() { alert('Hello Pragim'); }", true);
    Button1.Attributes["onclick"] = "AlertPragim()";
}

We have two different methods for placing JavaScript functions on an ASP.NET page - Page.ClientScript.RegisterStartupScript() and Page.ClientScript.RegisterClientScriptBlock() . What is the difference between these 2 methods.
Difference:
The main difference is that the RegisterStartupScript method places the JavaScript at the bottom of the ASP.NET page right before the closing </form> element. The RegisterClientScriptBlock method places the JavaScript directly after the opening <form> element in the page. This will have the following impact.

For an example of this, here is a way to put focus on a text box on a page when the page is loaded into the browser - using the RegisterStartupScript method:

Page.ClientScript.RegisterStartupScript(Me.GetType(), "Testing", "document.forms[0]['TextBox1'].focus();", True)

This works well because the textbox on the page is generated and placed on the page by the time the browser gets down to the bottom of the page and gets to this little bit of JavaScript. But, if instead it was written like this (using the RegisterClientScriptBlock method):
Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "Testing","document.forms[0]['TextBox1'].focus();", True)

Focus will not get to the textbox control and a JavaScript error will be generated on the page.The reason for this is that the browser will encounter the JavaScript before the text box is on the page. Therefore, the JavaScript will not be able to find a TextBox1
Placing entire JavaScript in a seperate .js file:
Having your entire javascript functions in a seperate file is always recomended because all your client side javascript is now at one place and not in the aspx or the code behind which will reduce much of the confusion. The following are the steps to have your entire javascript in one file and call it from your aspx page.

1. Right click on the project and click "add new item". Then choose jscript file. Name it as JavaScriptFile.js. All javascript files should have .js extension.
2. Right the Above AlertPragim() javascript function in the file and save it.
3. Include script tags as below in the <Head> seciton of the aspx page
  <script language="Javascript" type="text/javascript" src="JavaScriptFile.js"></script>
4.On the page_load event add - Button1.Attributes["onclick"] = "AlertPragim()"; 
When you click the button, the javascript function will be called.

Njoy Programming
   ByPrasad Cherukuri