Tie JavaScript events to ASP.NET objects
Published: 07 May 2003 10:40 BST
The ASP.NET Framework gives you enormous power and flexibility. You can create server-side code to handle any type of requirement, but nothing beats client-side JavaScript for many tasks. Adding JavaScript to an ASP.NET Web form is like adding it to any other type of Web page -- but binding code to ASP.NET form elements is not as simple.
Why JavaScript?
The merits of client-side JavaScript have been exhausted in other articles. The main advantage is performance. The same functionality is easily developed using C# or VB.NET, but it requires a roundtrip to the server and thus entails a performance hit. The JavaScript counterpart is downloaded with the page, and execution is confined to the browser with no server call. Common scenarios for this approach include field validation, confirmation dialog boxes, and opening other windows.
Let's review how you include JavaScript in a regular Web page. Then, we'll take a look at the extra steps needed to get JavaScript to play nice with ASP.NET Web forms.
Traditional Web forms
A regular Web page includes various standard areas, such as the head and the body. Normally, JavaScript functions are placed in the head portion of the form so that they are loaded before the body, making them immediately available. The functions are then called from HTML elements within the page body. As an example, let's look at the following JavaScript function:
function confirmSubmit() {
var doc = document.forms[0];
var msg = "Are you sure you want to submit this data?";
if (confirm(msg)) {
doc.submit();
} else {
// do nothing
} }
This function is simple: It asks the user to verify whether he or she wants to submit the document. The document is submitted if the user clicks Yes in the confirmation box; otherwise, nothing happens.
The function is easily connected to an HTML submit button:
<input type="button" value="submit" name="butSubmit" onClick="confirmSubmit();">
Once the user clicks the button, the message in Figure A appears.
Figure A
- Example JavaScript confirmation






