- Sample ASP.NET Web form
The key step is binding the ASP.NET button to the JavaScript function. This is accomplished by way of the Attributes property of the ASP.NET button UserControl object. The Attributes property contains an Add method allowing events to be added to the button. The following VB.NET code does the trick:
- butSubmit.Attributes.Add("onClick", "return confirmSubmit();")
Figure C shows the VB.NET code in the Visual Studio .NET environment.
Figure C
- Adding the function to the button
Personally, I find this syntax confusing, since I am accustomed to standard Web form syntax. But simply typing the standard onClick event into the ASP.NET Web form (HTML source) causes errors. I had to dig through documentation to discover the required syntax. Of course, the code can be extended. ASP.NET includes validation controls, but the JavaScript can easily be added and referenced using the code in this article. Let's take a look at validating two name fields before allowing submission. We'll extend the sample form from the first example to include the two text fields shown in Figure D. These fields are validated using the following JavaScript:
- function valSubmit() {
var doc = document.forms[0];
var msg = "";
var msg = "";
if (doc.txtFirstName.value == "") {
msg += "- First Name" + "\n";
}
if (doc.txtLastName.value == "") {
msg += "- Last Name" + "\n";
}
if (msg == "") {
doc.submit();
} else {
var valMsg1 = "The following required fields are missing.";
var valMsg2 = "Please complete and resubmit."
alert(valMsg1 + "\n\n" + valMsg2 + "\n\n" + msg);
return;
} }
- butSubmit.Attributes.Add("onClick", "return valSubmit();")
- Added text fields
Using the Attributes property of the button UserControl object to bind a JavaScript event is just one of the property's many applications. You can also use Attributes to alter the various colours tied to the control and to apply cascading style sheet elements, among other things. Examine the online help or other .NET documentation for more details. Don't reinvent the wheel
The Internet is full of sample JavaScript code that can tackle almost any task, so there is no reason to redo what has already been done. ASP.NET offers many powerful features, but the old stalwart JavaScript is great for handling common tasks and offloading processing to the client rather than the server.
For a weekly round-up of the enterprise IT news, sign up for the Tech Update newsletter. Let the editors know what you think in the Mailroom.






