>
 





ASP.NET provides a powerful server-based programming model with its postback architecture that allows performing all the work on the server while ensuring security and compatibility. 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 (submitting to the server).

JavaScript is embedded directly into an HTML web page. The code is downloaded to the client computer and executed by the browser.

The most straightforward approach for embedding small amounts of JavaScript code is adding directly to an event attribute for an HTML element. If you want to run the code automatically when the page loads, or react to a client-side event, you can add tag that contains the script code.

Usually, developers define a function in a block and then attach the function to a client-side event using an event attribute.

<script language="javascript">
   Function alertOnClick(){ alert(“Clicked!”);}
</script>
 

Protected void Page_Load(object sender, System.EventArgs e)
{
   button1.Attributes.Add(“onClick”,”alertOnClick();”)
}

Whether you use event attributes, script blocks or both, you may directly add static JavaScript code to the .aspx page or you may embed code by using the methods of the Page class.

The code above adds the onClick attribute to the button1 control. When the user click on the button, the event occurs and the JavaScript alert() function is called and “Clicked” message is displayed.

Usually, you have to insert JavaScript by adding attributes to a control with one exception. In button (button,linkbutton ,imagebutton) controls' clicks, you can use OnClientClick property.

<asp:button id="btnClick" runat="server"
     OnClientClick="return confirm('Sure?');"
     text="Click Me"/>

The button click still post back the page but before posting back, client side confirmation prompt is displayed.

Common approach for a large amount of code is to place a JavaScript function in a block and then call that function using an event attribute. This approach is even more practical, if you need to use the same code for several times.

The script blocks can be embedded anywhere in the header or the body of an HTML document, and a single document can have any number of script blocks. However, if you need to call a function, that function must be defined in a script block before the event attribute that calls it. Otherwise, it is better to place scripts to the end of the document. Progressive rendering is blocked until all JavaScript have been downloaded. Scripts cause progressive rendering to stop for all content below the script until it is fully loaded.

For more details: 7 Easy-to-Apply Tips to Improve Your Web Site Performance

The tag takes a language attribute that specifies the language and version. Browsers ignore script blocks for languages they don’t support.

You can also use the src attribute to embed external javascripts files. These files usually contain complex JavaScript. Using external files generally produces faster pages because the JavaScript files are cached by the browser.

It’s more flexible to render script blocks using the Page.ClientScript property, which exposes a ClientScriptManager object that provides several useful methods for managing script blocks. Two of the most useful are: RegisterStartupScript and RegisterClientScriptBlock.

RegisterClientScriptBlock() is designed for functions that are called in response to JavaScript events. YThese blocks can be placed anywhere in the HTML document. The RegisterStartupScript() is meant to add JavaScript code that will be executed immediately when the page loads.

When you use RegisterClientScriptBlock() and RegisterStartupScript(), you also specify a key name for the script block. For example, if your function shows an alert, you might use a unique key name such as ShowAlert. The purpose is to ensure that ASP.NET doesn’t add the same script function more than once.

protected void Page_Load(object sender, System.EventArgs e)
{
   string script = @"<script language='JavaScript'>
                                 function ShowAlert() {
                                    var msg = 'Submitted!!';
                                    return alert(msg);}
                           </script>";

  
  Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
    "ShowAlert", script);

  form1.Attributes.Add("onSubmit", "return ShowAlert();");
}

The build in Page.ClientScript object allows you to place JavaScript inside an ASP.NET page. We cannot use this object to place JavaScript code or JavaScript include file into the head section of the page.

Fortunately, Simone B created a library, to include/register scripts and style sheets into the head portion of an ASP.NET page.

For more details: HeadScriptManager - A class library for registering scripts into the page header with ASP.NET 2.0

Want automatic updates? Subscribe to our RSS feed or
Get Email Updates sent directly to your inbox!

Currently rated 5.0 by 5 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Comments

September 21. 2007 11:17

how can i do -> javascript value to asp.net value?

<script> var a = 10;</script>

<%
int b = 0;
%>

i want to the a value to b.

response.write b;

view: b=10

sorry.my english very poor. hehe....  Smile

little bird | Reply

November 7. 2007 21:29


Refer this Link for Using JavaScript in ASP.Net

www.dotnetrobert.com/.../Default.aspx

Rob | Reply

November 27. 2007 16:49

Hi everybody,I have a problem and i hope to be helped.
if (..)=true then
     ....
else
    'call javascript function
end if

NguyenLeNam | Reply

January 22. 2008 13:19

Hello Friends,
I want to know how to get a  messagebox that has yes/no buttons which ll work accordingly as specified in function(Ex: Are you sure to Delete? if we press 'Yes' then delete ll takes place and if it is 'No' then nothing ll takes place) in asp.net page.

San | Reply

May 19. 2008 11:04

How can we add more than one .JS file in our aspx page using Page.ClientScript.RegisterClientScriptBlock. or is there is any method to register Js file . i do'nt want to use AJax.

xion | Reply

January 15. 2009 23:27

The RegisterClientScriptBlock use the key internally in the server, It doesnt appear in the client; so you cant identify the script block with that. So you cant remove it.
BUT!!
The last parameter of RegisterClientScriptBlock lets you put your own tag. That tag can contain... lets say.. an ID. With this ID you cant remove it from the head element whenever you want.
For example, I use this in some UpdatePanel:
                ScriptManager.RegisterClientScriptBlock(UpdatePanel1, UpdatePanel1.GetType(), "MyScripts", _
                    "<script type='text/javascript' id='MyScripts'>" & _
                    "........." & _
                    "removeDuplicatedScript('MyScripts');</script>" _
                    , False)

And I made an include to the page with this cool functions that I build:
// Include a javascript file inside another one.
function include(filename)
{
  var head = document.getElementsByTagName('head')[0];
  
    var scripts = document.getElementsByTagName('script');
    for(var x=0;x<scripts.length; x++)
    {
        if (scripts[x].getAttribute('src'))
        {
            if(scripts[x].getAttribute('src').indexOf(filename) != -1)
            {
                head.removeChild(scripts[x]);
                break;
            }
        }
    }
  
  script = document.createElement('script');
  script.src = filename;
  script.type = 'text/javascript';
  head.appendChild(script)
}

// Removes duplicated scripts.
function removeDuplicatedScript(id)
{
    var count = 0;
  var head = document.getElementsByTagName('head')[0];
  
    var scripts = document.getElementsByTagName('script');
    var firstScript;
    for(var x=0;x<scripts.length; x++)
    {
        if (scripts[x].getAttribute('id'))
        {
            if(scripts[x].getAttribute('id').indexOf(id) != -1)
            {
                if (count == 0)
                {
                    firstScript = scripts[x];
                    count++;
                }
                else
                {
                    head.removeChild(firstScript);
                    firstScript = scripts[x];
                    count = 1;
                }
            }
        }
    }
}

I cant find any real answer to this topic so I hope I help someone with this!!!
Enjoy!

Lucas | Reply

January 24. 2009 07:53

good .thanks

anil | Reply

October 22. 2009 12:43

Social comments and analytics for this post

This post was mentioned on Twitter by bloggingdev: Using JavaScript with ASP.NET - http://su.pr/1yUSiH

uberVU - social comments | Reply

Add comment




(Will not be displayed!)








Free CMS