Developer

Combine JavaScript with ASP.NET Web forms

JavaScript provides an alternative for ASP.NET server-based controls, without the need to go to the server. Take a closer look at combining the power of JavaScript with ASP.NET.

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. Utilizing 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.\n\n" + 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 utilizes normal HTML form elements, but using it with an ASP.NET Web form isn't as straightforward.

Combining JavaScript with ASP.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.\n\n" + 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.

TechRepublic's free .NET newsletter, delivered each Wednesday, contains useful tips and coding examples on topics such as Web services, ASP.NET, ADO.NET, and Visual Studio .NET. Automatically sign up today!

About Tony Patton

Tony Patton has worn many hats over his 15+ years in the IT industry while witnessing many technologies come and go. He currently focuses on .NET and Web Development while trying to grasp the many facets of supporting such technologies in a productio...

Editor's Picks

Free Newsletters, In your Inbox