ASP.NET provides a new paradigm for developing Web-based applications. This includes a set of server-based controls that are analogous to HTML form elements such as text boxes, buttons, and so forth. The problem with these controls is the need to call the server. JavaScript provides an alternative for many tasks that negates the need to go to the server. Let's take a closer look at combining the power of JavaScript with ASP.NET.

Performance is a must

Making calls to the server requires bandwidth and server processing time. This may not be a problem with an intranet application, which has the advantage of a high-speed LAN, but an Internet application is a different story. An Internet user's connection speed varies depending on whether the user has a dial-up modem, DSL, or a cable modem. Utilising client-side JavaScript negates the need for a server round-trip.

The traditional approach

A standard Web form includes numerous standard areas such as the head, body, and form. JavaScript functions are traditionally placed in the head portion of the Web form. This allows the functions to be loaded and be available to the rest of the page. Once loaded, the functions may be called from HTML elements.

Let's take a look at a simple JavaScript example:


function valSubmit() {
var doc = document.forms[0];
var msg = "";
if (doc.firstName.value == "") { 
msg += "- Please enter a first name.n";
}

if (doc.lastName.value == "") {
msg += "- Please enter a last name.n";
}

if (msg == "") {
doc.submit();
} else {
alert("The following errors were
encountered.nn" + msg); } }

This function verifies that values are entered into two HTML fields on the form. If either field is empty, an error message displays and execution stops. If both fields are populated, the form is submitted. You may call this function from an HTML button with the following code:


<input type="button" value="submit"
name="btnSubmit" onClick="valSubmit();">

With this relationship, the form isn't submitted to the server until the fields are populated. The code may be simple, but it doesn't have any adverse effect on performance since no extra server calls are necessary; and the JavaScript code is short and sweet, which means the form doesn't require additional load time. This solution utilises normal HTML form elements, but using it with an ASP.NET Web form isn't as straightforward.

Combining JavaScript with ASP.NET

WEEKLY .NET HOW-TOS

New .NET tutorials updated every Thusday with Cast Your .NET

ASP.NET Web forms allow the use of standard HTML, so you can easily use the previous example--but it negates the power ASP.NET offers. ASP.NET User Controls allow you to call server code easily to process the Web form. Fortunately, it's possible to combine the power of the User Controls and JavaScript. I'll demonstrate this with an ASP.NET Button control.

The Button control's Attributes property provides a way to tie JavaScript to the control. First, the JavaScript function is placed on the ASP.NET Web form, but it's altered in a particular way: A return value is added. The function returns true if the validation is successful; this signals that the form may be submitted to the server. The submission to the server signals that the server function associated with the button is called. A return value of false signals the function failed, so the form isn't submitted.


<%@ Page language="c#" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html><head>
<title>WebForm1</title>
<script language="javascript">
function valSubmit() {
var doc = document.forms[0];
var msg = "";
if (doc.firstName.value == "") {
msg += "- Please enter a first name.n";
}
if (doc.lastName.value == "") {
msg += "- Please enter a last name.n";
}
if (msg == "") {
doc.submit();
return true;
} else {
alert("The following errors were encountered.nn" + msg);
return false;
} }
</script>
<script language="C#" runat="server">
private void btnSearch_Click(object sender, System.EventArgs e) {
Response.Write("Search");
}
private void Page_Load(object sender, System.EventArgs e) {
btnSubmit.Attributes.Add("onClick", "return valSubmit();");
}
</script></head>
<body>
<form id="frmBuilderTest" method="post" runat="server">
<label style="Z-INDEX: 101; LEFT: 10px; POSITION: absolute; TOP: 48px"><
First Name:</label>
<input style="Z-INDEX: 102; LEFT: 88px; POSITION: absolute; TOP: 48px"
type="text" name="firstName" id="firstName">
<label style="Z-INDEX: 103; LEFT: 10px; POSITION: absolute; TOP: 88px">
Last Name:</label>
<input style="Z-INDEX: 104; LEFT: 88px; POSITION: absolute; TOP: 88px"
type="text" name="lastName" id="lastName"><br /><br /> <asp:Button id="btnSubmit" style="Z-INDEX: 105; LEFT: 64px; POSITION: absolute; TOP: 128px" runat="server" Text="Submit" Width="136px" OnClick="btnSearch_Click"></asp:Button> </form></body></html>

This is the key line in the code:


btnSubmit.Attributes.Add("onClick", "return valSubmit();"); 

The elements are placed on the HTML form using CSS via their style attribute. The form ties the JavaScript function to the ASP.NET Button (btnSubmit) and to its HTML onClick event. The OnClick attribute of the ASP.NET Button tells the system what function is called when the form is submitted to the server.

If you're a VB.NET developer, the only change to the previous code is the C# block of code. The VB.NET version follows:


<script language="vb" runat="server">
Private btnSearch_Click (sender As Object, e As System.EventArgs)
Response.Write("Search")
End Sub
Private Page_Load(sender As Object, e As System.EventArgs)
btnSubmit.Attributes.Add("onClick", "return valSubmit();")
End Sub
</script>

A powerful combination

JavaScript is the de facto standard for client-side Web development. Combining it with ASP.NET Web forms provides the developer with a powerful set of tools for building robust applications that consider performance a key ingredient.

Tony Patton began his professional career as an application developer earning Java, VB, Lotus, and XML certifications to bolster his knowledge.

Do you need help with .Net? Gain advice from Builder AU forums

Related links

Comments

1

Oscar Spila - 07/10/04

Why the code:

private void btnSearch_Click(object sender, System.EventArgs e) {
Response.Write("Search");

in Opera and Netscape not work? but en IE is work?

» Report offensive content

2

Tejas Shah - 12/02/05

Hello evreyone
I also have the same problem
but i also want to get back the return value of function.
Then how can i get that valuewith vb.net in asp.net

thanks in advance

» Report offensive content

3

Bradley Thomas - 18/04/05

this article shows what i find everywhere on the web, how to link from your asp.net page to your html/javascript page, but not the other way around. i would love to know how to get details that have been changed through javascript back to my asp.net page so that they may be stored in the database. how do i do this

» Report offensive content

4

Ravi - 28/04/05

How to access C# Label controls in Javascript. All other Controls I can access only Lables i cant. Please help.

» Report offensive content

5

Steven Oesterreicher - 04/10/05

Isn't using java Script frowded upon because you don't know whether a client has Java Script turned on?

» Report offensive content

6

Rajib Ahmed - 10/05/06

Using Javasript is not frowned upon. Client side validation is necessary, but doesn't imply Server Side validation is not. It only makes applications stronger to have validation on both sides. If you are using Client/Server side validation, make sure in you VB.NET or C# code checks if the Page is Valid. (Page.IsValid)

» Report offensive content

7

Sagar - 21/07/06

Hello everyone,
I want to add a javascript function on my project's one .aspx file to validate a textbox so that the charector '&' should not be entered in it

» Report offensive content

8

NewASP.NETTER - 11/08/06

What to do if "onClick" event already defines something else?

» Report offensive content

9

Smruti Ranjan Rout - 14/08/06

Hello everyone
if i want call a java script function in onClick of a button attribut,
if i am writing btnSubmit.Attributes.Add("onClick","return checkRequiredField();");

Regular Expression Validator dosn't work

what i should do???

» Report offensive content

10

Bill Donnelly - 06/09/06

In my situation, I have some logic which occurs as the page (C#/ASP.NET) gets loaded (it determines whether the record the user is trying to edit is locked by another user).
I want to give the user the opportunity to take some action; the only way to get a yes/no answer (AFAIK) is to use a javascript confirm() dialog.

The code is already in the process of handling an action (onload) so I can't fire the javascript from a button click or anything. I need to fire the javascript and get the return value from the function, so that the following C# code can choose action A or B based on the result.

How can I do this? It's frustrating that I can call the javascript code to present the dialog (by doing Response.Write() with the script) but it doesn't seem to be possible to get the result value.

Code here shows the basic outline of my loadPage() function with the unrelated junk stripped out.

public void loadPage(object sender, System.EventArgs e) {
if ( ! IsPostBack ) {
if ( recordIsLocked() ) {
lockFields();
string lockedMessage = "Send email to lock owner?";
Response.Write("<SCRIPT>return confirm('"+
lockedMessage +"');</SCRIPT>");
// Is there any way to make the script store the
// return value somewhere that can be checked
// from the C# world?
} else {
lockRecord();
}
}
}

» Report offensive content

11

Dev Bhagat - 12/09/06

Thanks for this wonderful article.
This Script is working very fine in dotnet 1.1

Now, I just shifted to 2.0 version, this is no more working there.

Please tell me what to do, If I have to code it in a master page as there is no Form tag available there.
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">

</asp:Content>

» Report offensive content

12

engin dikici - 03/11/06

Perfect article; solved my problems.

Thank you ver much.

» Report offensive content

13

Asim - 17/11/06

hi

I want ot call javascript function on OnSelectedIndexChanged event of asp.net. what can i do?

thanks
regards

» Report offensive content

14

vinod - 15/02/07

HI,
I have html server control with required field validator and it was working fine when i click on save button.

Now i have added the OnClientClick="return confrim('Are your sure');" with save button, and conform dialog box is working fine but the required fields validator with the html controls are by passed and not working.

thanks
vinod

» Report offensive content

15

Charles - 28/02/07

How do I combine javascript and asp.net when using master page.
I tried your function on a regular asp.net form and it worked perfectly. However, it does work out on a content page when using asp.net 2.0 master page. I need your help to fix this problem. Thanks

» Report offensive content

16

krishna agrawal - 02/04/07

How can i Pop-up a window in button click in asp.net?

» Report offensive content

17

David - 18/05/07

I want to call an javascript function whenever i am deleting an row in datagrid. I have an imagebutton in itemtemplate and i am caling javascript function which returns true of false. whenever i am clicking th imagebutton i am getting the javascript function but after that i need to get the return value from the javascript functiont to datagrid rowcommand event. please help me regarding this.

» Report offensive content

18

kuldeep - 14/06/07

this is very short and unsufficient example ...

no thanks

» Report offensive content

19

Deepak - 13/08/07

Give me code for opening a form in diffrent style

» Report offensive content

20

Deepak - 13/08/07

Give me code for opening a form in diffrent style

» Report offensive content

21

Deepak - 13/08/07

Give me code for opening a form in diffrent style

» Report offensive content

22

Meenu - 05/09/07

I have to call a html page using the javascript in the specified portion of the page without using frames.

» Report offensive content

23

Sumiya - 13/12/07

I wish to know if a JavaScript code can be called from an asp.net webcontrol(not HTMLcontrol). e.g. I wish to populate a drop down list (webcontrol) using JavaScript, how do i go about it? I know that HTMLcontrols can be used, but my application isn't suited to that. Please explain.

» Report offensive content

24

Oguz Altuncu - 31/12/07

To answer Charles' question:
THis is a great article but I have the same issue as I m using master pages too. The reason is,
The ID of the input box will be modified if you use masterpages( ctl00_ContentPlaceHolder1_txtLastName in my case), to get the new ID of the control, you can add something like this to your html
<input id="txtLastName" runat="server" type="text" onfocus="alert(this.id)" />




Charles - 28/02/07

How do I combine javascript and asp.net when using master page.
I tried your function on a regular asp.net form and it worked perfectly. However, it does work out on a content page when using asp.net 2.0 master page. I need your help to fix this problem. Thanks
» Report offensive content

<input id="txtLastName" runat="server" type="text" onfocus="alert(this.id)" />

» Report offensive content

25

suma - 23/01/08

how 2 call a js function in when selectedIndexChanged of a ListBox

» Report offensive content

26

Hari - 11/04/08

How do you submit a form similarly on .NET 2.0 in content Pages, where this page would be on a contentplaceholder on a masterpage. How do you need to change this? Would appreciate any pointers !! Thank you.

» Report offensive content

27

venky - 17/06/08

28

sravani0711 - 24/07/08

how do u would registration and user login,customer registration and books catalog(ordered and unordered) program in HTML and CSS?
please give me

» Report offensive content

29

Yogini Patil - 30/08/08

please tell me how can I call javascript function in content tag in c#.

I want to validate the whole form on linkbutton click which is in content tag

<asp:Content ID="Content2" ContentPlaceHolderID="head1" Runat="Server">
<form name="AddUserFrm">
<table>
// other controls
<asp:LinkButton ID="lnk" runat="server"
OnClick="check_Click" OnClientClick="return ChkAddUser();">ADD</asp:LinkButton>
</table>
</form>

» Report offensive content

30

Rashmi Rawale - 18/09/08

Sir,

I want to know about how to add javascript file in asp.net form and
what will be coding for add javascript to asp.net

» Report offensive content

Leave a comment

You must read and type the 6 chars within 0..9 and A..F

* indicates mandatory fields.

30

Rashmi Rawale - 18/09/08

Sir, I want to know about how to add javascript file in asp.net form and what will be coding for add javascript ... more

29

Yogini Patil - 30/08/08

please tell me how can I call javascript function in content tag in c#. I want to validate the whole form on ... more

28

sravani0711 - 24/07/08

how do u would registration and user login,customer registration and books catalog(ordered and unordered) program in HTML and CSS? please give me ... more

Log in


Sign up | Forgot your password?

  • Staff XP stays on life support for longer

    This week's Roundup looks at Microsoft's decision to extend the life of Windows XP, the release of Microsoft Surface SDK, Firefox's new Geode plug-in, Yahoo's new tool -- Smush It and more. Read more »

    -- posted by Staff

  • Chris Duckett The good and truly awful celluloid depictions of computers

    Ever wonder why your lawyer uncle leaves the room whenever you turn over to Boston Legal? Or why your forensic science cousin can't stand crime drama? You know the answer: it’s the horrid trivialisation and dumbing down of an occupation to make it appear entertaining. Sometimes it is so unbelievable that it actually hurts and yelling at the screen is the only outlet. Read more »

    -- posted by Chris Duckett

  • Brendon Chase Apple's iPhone engineers to tour Sydney, Melbourne

    Aussie developers will be able to get up close and personal with some of the iPhone engineers in November to learn how to build applications for the platform. Read more »

    -- posted by Brendon Chase

What's on?