Creating a ASP.NET Contact Form [con't]
Creating Placeholder controls
Before moving on, we need to add two place holder controls to our page. Right now, if we were to submit our form, other than an email being delivered to our inbox, there would be no visual indication of a successful submission. As a result, we need to provide a message to our visitor's informing them of a successfully sent email.
We have two options: (1) after sending the email, use a redirect to send our visitors to a separate success page, or (2) create place holder controls that will show or hide content based on success or failure. Generally, for the sake of maintenance, it's wise to keep everything in one file. In order to create these controls, open contact.aspx and add the following controls as shown below:
As you can see from the example above, right after our opening body tag, we create a place holder control named formPH and set it's visibility to true. Since it has the contents of our form, we want to show it initially. Then, right before the closing body tag, we add another place holder control named successPH and set its visibility to false. Continuing, open contact.aspx.cs and add the following code as shown below:
Extending the reset event handler
Right now, there's no way to clear our form fields of existing data. Let's fix this by adding the code shown below to our existing reset event handler:
As you can see from the example above, we set each web control's text property to an empty string. Save your file, refresh your browser; fill in some fields and press reset.
Validation
Since we have created our form, and it's sending the information we need, we need to implement functionality that ensure our fields are filled in before sending the email. Generally, when you provide forms for your visitors to fill out, you want a certain amount of information entered before it's allowed to submit the email to the specified recipient. Validation can be done one of two ways or both, just depends on how much you want to foolproof your form.
The first way is to use client-side validation using JavaScript, which is only performed client-side, in other words, only executed on the visitor's computer. This is often done to provide instant feedback to the visitor as to any errors that occurred. There's only one disadvantage to relying on this approach: if JavaScript is disabled in a visitor's browser, then validation fails to execute, leaving your web form with empty details that you may require.
The second way is use server-side validation using the behaviors present within your server-side language. This method is far more reliable because even if a visitor has JavaScript disabled in a browser, server-side validation scripts can still execute from the server and provide feedback as to any errors that occurred.
Generally, it's recommended to use a combination of both, that is, using JavaScript to ensure instant feedback that limits post backs to the server, and then using server-side scripts to check sensitive fields to ensure that the visitor did in fact give you the information you need.
Creating required fields in ASP.NET
Generally, in PHP and ASP, you create a separate JavaScript file that contains functions to check fields for empty values. Then, within your page, usually at the top, you would provide server-side validation to ensure those same fields do in fact contain a value. In essence, you have two files. In the ASP.NET environment, they made this process much easier and a bit more intuitive. When Microsoft created ASP.NET, they decided to package it with an additional set of controls that are effectively grouped together in a set of validation controls. Out of this group and arguably the easiest to use are required field validators, which do exactly what they are called: they require that certain fields are filled in before allowing the form to submit, more importantly however, they produce the JavaScript automatically for us. Let's go back to contact.aspx and modify our code as shown below:
As you can see from the example above, we have used required field validators to validate each text box. The validation controls parts are:
- ID: Each control must have a unique ID which allows us to identify it if the need arises
- Runat=server: Instructs this control to be run by the server
- ControlToValidate: Instructs our validation controls which control (s) we want to validate, in our case, each corresponding text box control
- ErrorMessage: Provides error messages to our visitors informing them of the errors present
- Display=Dynamic: Is set to ensure the error messages would not be in source code until they are executed.
After saving your file with the new controls, refresh your page in your browser, leave all fields empty and click the submit button, you should have four error messages as shown below:
It should be noted the placement of these controls is essential. The error messages for the controls will show wherever the control is placed. Since we placed the validation controls right before the closing table cell for each web control, the error messages are shown right after the controls.
You don't see error messages?
If your error messages don't show, it likely means that you're missing the validation JavaScript file in the default installation of IIS, which is at the following directory location:
C:\Inetpub\wwwroot\aspnet_client\system_web\1_1_4322
The file is appropriately named WebUIValidation.js. To fix this issue, run the following command from the command prompt:
C: \WINDOWS\Microsoft.NET\Framework\[version]\ aspnet_regiis.exe -c
It should be noted that by default, all virtual directories point to the local installation of IIS. As a result, the ability for your virtual directory to see this file shouldn't be an issue, unless of course, it's not there.
Enabling server-side validation
Even though we have established client-side validation, if JavaScript is disabled in a visitor's browser, the validation controls that produce JavaScript will fail. Fortunately, ASP.NET makes the server-side check quite easy to implement. Switch back to your code-behind file and modify the send mail event to the following as shown below:
As you can see from the example above, we perform a conditional check within our send mail event. Inside the check, we perform a Boolean check on the IsValid property, which essentially checks the values of all our controls in our page. As a result, if any of the controls come back as false, meaning they're empty, we issue a return statement that stops the rest of the event from firing and provides our visitor with an error message as to what went wrong. If all controls that we require come back as true, meaning they're filled in, then the rest of our send mail event is allowed to execute, and subsequently, send our email message. Save your file, disable JavaScript and leave a few fields blank, and the error messages should show. At this point, we have a completed file that is ready and working.
Publishing your file
When publishing your file to your remote server, make sure to create an application where this form can reside and change the relay server where appropriate.
Sending a test email
Presuming the SMTP client is configured correctly on the remove server, go ahead and fill in our fields, click submit, and you should get an email from our form delivered to your inbox in a few minutes.
View State
One more important concept should be mentioned before finishing the article. By default, the web is a stateless environment. In essence, when you visit a website and navigate between different pages, the website has no idea what page you last visited. Often times, when writing websites that have dynamic activity such as displaying categories, and their associated products, web programmers will use a query string so that a web page can remember where it came from, and then display the associated content.
In our case, when visitors submit form fields with validation enforced, if errors occur, the page post backs to the server and any existing information in the fields is lost. In PHP or ASP, the only way around this was to create a variable for each form field, and set it to the request value of the form field, and then evaluate the variable value out, which is a pain.
With ASP.NET, they have resolved this issue by a concept called view state. In essence, view state is enabled when you use a form tag, which if you remember from earlier in the article, form tags are created by default on all web forms. More importantly, view state is a hidden input tag with a special value used by the ASP.NET engine that keeps the values of our web controls stored in memory. This is important when you enforce validation on your web forms. Instead of creating additional variables, ASP.NET does the hard work for us. If you visit our file in the browser, fill in a couple fields, but leave the other two empty, press submit, you'll notice when the page posts back to the server, the existing information in the first two fields is still there, done automatically by ASP.NET!
However it should be noted that view state doesn't solve the problem of websites remembering the last page visited through a stateless environment, such as the query string method mentioned in our earlier category to products example. Also, it should be noted that additional web controls produce a larger view state, which can affect performance, something to keep in mind as you continue your work with web controls.
Summary
In this article, you learned how to create a contact form using ASP.NET. Additionally, you learned the following:
- How to download and install:
- .NET framework
- Visual Web Developer Express
- How to install a local web server, Internet Information Services (IIS)
- The .NET framework and the integration of ASP.NET
- How to create a web form and its associated code-behind file
- Within ASP.NET environment:
- Web controls, such as text boxes and their associated properties and values
- How to create event driven methods
- Validation controls that make client and server-side validation a breeze
- View state and it's relation to the stateless web environment
From the knowledge gained in this article, one should be able to take this simple web form, identify the information needed, be able to validate form fields, as well as send information collected to a specified email address. As a result, this web form could be modified to meet the needs of any web application for a business, company or organization to meet the needs of their customers, keep needless email from spamming our system, in a more intuitive, reliable and secure method.
If you have questions, please follow the link below:
https://midwestwebdesign.net/tutorials/contact.aspx
Ryan Butler is the founder of
Midwest Web Design. His skill sets include HTML, CSS, Flash, JavaScript, ASP.NET, PHP and database technologies.
Original: June 29, 2009