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

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Currently rated 5.0 by 4 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

November 7. 2007 21:29


Refer this Link for Using JavaScript in ASP.Net

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

Rob

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

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

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

Add comment





(will not be displayed)








  • javascript
  • querystring
  • url parameters
  • parse querystring
  • delayed redirect
  • settimeout
  • focus
  • textbox
  • page load
  • after submit
  • set focus in asp.net 2.0/3.5
  • on page load
  • after postback
  • set control focus
  • postback
  • asp.net 1.x
  • substring
  • substr
  • javascript string methods
  • parsefloat
  • convert strings to numbers
  • parseint
  • javascript history
  • history.go
  • history.back
  • http requests
  • image maps
  • css sprites
  • external css
  • external javascript
  • compress javascript
  • javascript compression
  • ajaxcontroltoolkit
  • tab control
  • array
  • length
  • javascipt
  • lastmodified
  • mstsc
  • terminal services
  • remote desktop connections
  • null
  • undefined
  • array.join
  • string concatenation
  • setinterval
  • clearinterval
  • timing events
  • cleartimeout
  • javascript timing events
  • url redirection
  • location.href
  • location.replace
  • redirect
  • redirection
  • system.io.compression
  • viewstate compression
  • compress viewstate
  • gzipstream
  • loadpagestatefrompersistencemedium
  • savepagestatetopersistencemedium
  • form spam
  • captcha
  • prevent spam without captcha
  • url redirect
  • defaultbutton
  • enter key
  • default button
  • asp.net
  • 2.0
  • form
  • panel
  • 1.1
  • form submit
  • dopostback
  • onkeypress
  • onkeydown
  • onkeyup
  • javascript key events
  • keycode 13
  • disable enter key
  • int32.parse
  • convert.toint32
  • int32.tryparse
  • google
  • hoax
  • gmail
  • storage
  • counter
  • mail
  • visual studio 2005
  • vs 2008
  • copy
  • paste
  • clipboard data
  • static variables
  • application object
  • static property
  • server control
  • web file manager
  • iz web file manager
  • convert
  • parse
  • tryparse
  • file upload control
  • maxrequestlength
  • executiontimeout
  • httpruntime
  • asp.net 2.0
  • registering scripts
  • registerclientscript
  • registerstartupscript
  • cross-browser
  • events
  • improve web site performance
  • compression
  • caching
  • elmah
  • error logging
  • exception
  • error
  • httphandler
  • google sitemap generator
  • sitemap
  • internet information services
  • iis7
  • hosts file
  • localhost
  • windows vista
  • search engine optimization
  • seo
  • search engine friendly pages
  • headscriptmanager
  • class library
  • head
  • css
  • c#
  • iis
  • internet information services manager
  • 401.3 unauthorized
  • 500.0 internal server error
  • http error 500.19
  • google toolbar
  • yellow input fields
  • input
  • select
  • background color
  • mozilla firefox
  • medium trust
  • orcas
  • compileroptions
  • warninglevel
  • zyb
  • mobile phones
  • online backup service
  • online services
  • textarea
  • maxlength
  • limit input length
  • custom server control
  • internal error 2739
  • adobe cs3
  • adobe customer support
  • solution
  • error code 0x80004005
  • 500.19 internal server error
  • meta tags
  • keywords meta tag
  • meta
  • description meta tag
  • fake page rank domains
  • scammers
  • google page rank technology
  • ebay
  • general
  • title
  • page rank