Page 1 of 1

ASP.NET Contact Form Tutorial

#1 psyking  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 20
  • View blog
  • Posts: 165
  • Joined: 17-January 10

Posted 27 July 2010 - 12:01 AM

Hey everyone,
I have always been tired of having to make a contact form every time I make a web page, and I figured everyone else was too. So I have created this tutorial with the idea that people will be able to use this to make their own ASP.NET contact form that you can use over and over again very easily. Plus this helped me get around to making my contact form. :D

Which is better?
Is using a premade tool that you found online better? Or is using your own custom contact form better? It depends on whether or not you wish to be able to customize it to your fitting.
The benefits of using a premade form:
  • Ready to use, just add and you’re ready
  • No knowledge of code needed to make it.
    The benefits of making your own:
  • You can customize it to your liking
  • You will understand C# and ASP.NET a little better

Requirements:
  • Some knowledge of C#
  • Microsoft Visual Studio 2010 Express (MS VS 2010) or Microsoft Visual Studio 2010 Professional (MS VS 2010) (College Students can download MS VS 2010 Pro for free here DreamSpark)
  • Some knowledge of ASP general tools
  • Some knowledge of Regular Expressions

What are you going to learn?
You are going to learn how to create a contact form and how to implement it into your ASP.NET website.

Contact Form Info
The contact form is used in many websites in order to allow customers or site users to contact the company or webmaster about inquiries or comments or even (hopefully not) complaints that they have towards something about either your site or business, or even something entirely different (most likely spam then).

Pre-Steps to Getting Started
Before we get started, you will need to open your version of MS VS 2010 and click the “New Project” link. On the side menu on the left, select Visual C# and then Web. On the right, select ASP.NET Empty Web Application. In the textbox labeled “Name”, type in whatever you wish to call your project. Then press “OK”. It will create the solution for the project, and after, you should have a blank screen. If the Solution Manager is not visible on the right side of the screen, go to the main menu and press “View”, then click on the Solution Manager. Right-click (for right-hand mice) or left-click (for left-hand mice) and move down to “Add”, then select “Add New File”. A box will pop up, and you will need to select “Web User Control”. Choose the name for what you wish to call it and press “OK”. A screen with the code:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Email Form.ascx.cs" Inherits="Email_Form.EmailForm" %>


will show up. Open the code behind file, found by pressing the arrow next to your user control on the solution manager. The code behind file will look like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace EmailForm
{
    public partial class EmailForm : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
    }
}


the only reason that it wouldn’t look the same, is because you may not have called your contact form by the same name. Alright, we are ready to begin.

Getting Started:

Step 1 – Designing the Form
Bring the page that is the design of your control back up, either by selecting the tab or by double clicking the file on the treeview. The first thing that we are going to add to our form is an ASP.NET Panel. Add it by placing these lines of code under the first line:
<asp:Panel runat=”server”>
	
</asp:Panel>


This creates a panel object, which keeps the controls together and allows for customizing the border and background of the control.

Inside of the panel that we have just created, we are going to have our contact form. The first thing that we need to collect from the person trying to contact us is their name, so, we will create the design for that first :D

Add this line of code in between the panel tags:
<asp:Label runat=”server”>Name:</asp:Label>
<asp:Textbox ID=”txtName” runat=”server”></asp:Textbox>
<br />


The label allows the people to see what to type into the textbox that we have also just added. The next important part is for them to give us their email, so that we may be able to reply to their inquiry/comment/complaint.

Add these lines of code underneath the last break:
<asp:Label runat=”server”>Email:</asp:Label>
<asp:Textbox ID=”txtEmail” runat=”server”></asp:Textbox>
<br />


This allows them to enter their email address so that we may reply to them. The next part is the subject, so that we will know what they are inquiring/commenting/complaining about.

Add these lines of code after the last break:
<asp:Label runat=”server”>Subject:</asp:Label>
<asp:Textbox ID=”txtSubject” runat=”server”></asp:Textbox>
<br />


This adds the subject line to the contact form. The most important part of the form is the next part, the part where they add the message to us.

Add these lines of code below the last break:
<asp:Label runat=”server”>Message:</asp:Label>
<textarea runat=”server” ID=”txtMessage” rows=”7” cols=”24”></textarea>
<br />


This adds the message, the content of the email, to the form. The final step is adding the send and clear buttons to the form, to do this, add the following lines of code underneath the last break:
<asp:Button runat=”server” ID=”btnSend” Text=”Send” />
<asp:Button runat=”server” ID=”btnReset” Text=”Reset” />


We now have a form that looks like a contact form, but actually does nothing yet.

The complete code for this part looks like this:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Email Form.ascx.cs" Inherits="Email_Form.EmailForm" %>
<asp:Panel runat="server" style="margin-bottom: 32px">
    <asp:Label runat="server">Name:</asp:Label>
    <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
    <br />
    <asp:Label runat="server">Email:</asp:Label>
    <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
    <br />
    <asp:Label runat="server">Subject:</asp:Label>
    <asp:TextBox ID="txtSubject" runat="server"></asp:TextBox>
    <br />
    <asp:Label runat="server">Message:</asp:Label>
    <textarea runat="server" id="txtMessage" rows="7" cols="24"></textarea>
    <br />
    <asp:Button runat="server" ID="btnSend" onclick=”btnSend_Click” Text="Send" />
    <asp:Button runat="server" ID="btnReset" onclick=”btnReset_Click” Text="Reset" />
</asp:Panel>



Step 2 – Adding Functionality to the Form
It is time to make our contact form a complete and working form, so to do that, we will need add a script tag that declares the type as Text/C# to the page. Add these lines of code under the first line and before the panel:
<%@ Import Namespace=”System.Net.Mail” %>
<%@ Import Namespace=”System.Net” %>
<script runat=”server” type=”text/C#”>
public void btnSend_Click(object sender, EventArgs e){
	MailMessage msg = new MailMessage();
	msg.To.Add(new MailAddress(“Your Email”));
	msg.From = new MailAddress(txtEmail.Text);
	msg.Subject = txtSubject.Text;
	msg.Body = txtName.Text + Environment.Newline + txtMessage.Value;
	SmtpClient client = new SmtpClient();
	client.Host = //Place your smtp server in quotation marks (i.e. “smtp.live.com”)
	client.Port = // Place your smtp port here, i.e. hotmail’s smtp port is 587
	client.Credentials = new NetworkCredential(“Your username”,”Your password”);
	client.EnableSsl = true;
	client.Send(msg);
}
public void btnReset_Click(object sender, EventArgs e){
	txtName.Text = “”;
	txtEmail.Text = “”;
	txtSubject.Text = “”;
	txtMessage.Value=””;
}
</script>


Now, to go into detail in what those lines of code do.

<%@ Import Namespace=”System.Net.Mail” %>
This line of code imports the Mail namespace in System.Net, allowing us to use the classes of MailMessage, MailAddress, and SmtpClient.

<%@ Import Namespace=”System.Net” %>
This line of code imports the Net namespace, which allows us to use the NetworkCredentials for the SmtpClient server credentials.

<script runat=”server” type=”text/C#”>
This tells the server that we are using text and C# in the design page, which allows us to do all of these cool functions.

public void btnSend_Click(object sender, EventArgs e){
This is us creating our click function for our send button. public allows us to actively access this function any time we initiate this class. void allows us to not have to return anything at the end of the function, and a little more as well. btnSend_Click is the function we are creating. object sender – this is the object that is sending the command to use this function. EventArgs e – these are the arguments that are sent in from the button that was pressed.

MailMessage msg = new MailMessage();
This creates the message that is going to be sent to the email address that you supply as the “to” email address.

msg.To.Add(new MailAddress(“Your Email”));
msg.From = new MailAddress(txtEmail.Text);
msg.Subject = txtSubject.Text;
msg.Body = txtName.Text + Environment.Newline + txtMessage.Value;

These lines add the actual message to msg, so that we can read it when they send it.
new MailAddress(“Your Email”));
This is the MailAddress class, mentioned earlier. The “To” and “From” and “Cc” and “Bcc” on the MailMessage class are returning MailAddress(es), so, we need to use the MailAddress class when setting one of those.

SmtpClient client = new SmtpClient();
This is how we are going to be sending the email to ourselves, using SMTP. The SmtpClient uses
  • Host
  • Credentials
  • Port
  • SSL
  • Send

to send the email.
We set the host equal to our smtp server location, like for example Windows Hotmail’s smtp server is smtp.live.com. The port we set equal to the server’s smtp port, and an example is Windows Hotmail’s smtp port 587. The credentials are NetworkCredentials which take a username and a password for the smtp server, like for example, say you have a hotmail account: example@hotmail.com with the password of: ilikecheese. Your NetworkCredentials would consist of those two things, the username and the password. SSL, EnableSsl, only enable this if your server requires SSL. And finally the send function sends a MailMessage that has been created.

The Reset Button function just resets all the textboxes and textareas and makes them empty.

The complete code for this section is:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Email Form.ascx.cs" Inherits="Email_Form.EmailForm" %>
<%@ Import Namespace="System.Net.Mail" %>
<%@ Import Namespace="System.Net" %>
<script runat="server" type="text/C#">
    public void btnSend_Click(object sender, EventArgs e){
        MailMessage msg = new MailMessage();
        msg.To.Add(new MailAddress("Your email"));
        msg.From = new MailAddress(txtEmail.Text);
        msg.Subject = txtSubject.Text;
        msg.Body = txtName.Text + Environment.NewLine + txtMessage.Value;
        SmtpClient client = new SmtpClient();
        client.Host = "Your host";
        client.Port = 25;
        NetworkCredential cred = new NetworkCredential("Your username", "Your password");
        client.Credentials = cred;
        client.EnableSsl = true;
        client.Send(msg);
    }
    public void btnReset_Click(object sender, EventArgs e)
    {
        txtName.Text = "";
        txtEmail.Text = "";
        txtSubject.Text = "";
        txtMessage.Value = "";
    }
</script>
<asp:Panel runat="server" style="margin-bottom: 32px">
    <asp:Label runat="server">Name:</asp:Label>
    <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
    <br />
    <asp:Label runat="server">Email:</asp:Label>
    <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
    <br />
    <asp:Label runat="server">Subject:</asp:Label>
    <asp:TextBox ID="txtSubject" runat="server"></asp:TextBox>
    <br />
    <asp:Label runat="server">Message:</asp:Label>
    <textarea runat="server" id="txtMessage" rows="7" cols="24"></textarea>
    <br />
    <asp:Button runat="server" ID="btnSend" onclick="btnSend_Click" Text="Send" />
    <asp:Button runat="server" ID="btnReset" onclick="btnReset_Click" Text="Reset" />
</asp:Panel>



Step 3 – Validation
Right now we have a workable contact form, however, what happens if the user doesn’t enter some data? If it’s the email address, an error will occur and the email won’t get sent, plus the user will be able to see the server side code if you haven’t defined a custom error page to redirect the user to. So to prevent this, we need to make sure they enter all the data correctly. Thankfully, ASP.NET provides an easy way to do this – ASP.NET Validation Server Controls.

The first validation control that we are going to use is the Required Field Validator. The Required Field Validator checks to make sure that the user has entered something into the field that we require be entered.
Place this line of code underneath the ASP.NET Textbox for the user’s name:
<asp:RequiredFieldValidator runat=”server” ErrorMessage=”Please enter the information requested.” ControlToValidate=”txtName”></asp:RequiredFieldValidator>


The code for the Name field should then look like this:
    <asp:Label runat="server">Name:</asp:Label>
    <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
    <asp:RequiredFieldValidator runat="server" ErrorMessage="Please enter the information requested." ControlToValidate="txtName"></asp:RequiredFieldValidator>
    <br />



We are going to add a Required Field Validator for each of the fields, so to continue with that, add this line underneath the Email field:
<asp:RequiredFieldValidator runat=”server” ErrorMessage=”Please enter the information requested.” ControlToValidate=”txtEmail”></asp:RequiredFieldValidator>



Then, add this underneath the code for the subject field:
<asp:RequiredFieldValidator runat=”server” ErrorMessage=”Please enter the information requested.” ControlToValidate=”txtSubject”></asp:RequiredFieldValidator>



Then underneath the message field:
<asp:RequiredFieldValidator runat=”server” ErrorMessage=”Please enter a message.” ControlToValidate=”txtMessage”></asp:RequiredFieldValidator>



The Required Field Validator shows the error message next to the control that it is validating if it fails the validation. So if I didn’t enter a name, the message “Please enter the requested information.” would appear next to the name field.

The final code should look like this:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Email Form.ascx.cs" Inherits="Email_Form.EmailForm" %>
<%@ Import Namespace="System.Net.Mail" %>
<%@ Import Namespace="System.Net" %>
<script runat="server" type="text/C#">
    public void btnSend_Click(object sender, EventArgs e){
        MailMessage msg = new MailMessage();
        msg.To.Add(new MailAddress("Your email"));
        msg.From = new MailAddress(txtEmail.Text);
        msg.Subject = txtSubject.Text;
        msg.Body = txtName.Text + Environment.NewLine + txtMessage.Value;
        SmtpClient client = new SmtpClient();
        client.Host = "Your host";
        client.Port = 25;
        NetworkCredential cred = new NetworkCredential("Your username", "Your password");
        client.Credentials = cred;
        client.EnableSsl = true;
        client.Send(msg);
    }
    public void btnReset_Click(object sender, EventArgs e)
    {
        txtName.Text = "";
        txtEmail.Text = "";
        txtSubject.Text = "";
        txtMessage.Value = "";
    }
</script>
<asp:Panel runat="server" style="margin-bottom: 32px">
    <asp:Label runat="server">Name:</asp:Label>
    <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
    <asp:RequiredFieldValidator runat="server" ErrorMessage="Please enter the information requested." ControlToValidate="txtName"></asp:RequiredFieldValidator>
    <br />
    <asp:Label runat="server">Email:</asp:Label>
    <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
    <asp:RequiredFieldValidator runat="server" ErrorMessage="Please enter the information requested." ControlToValidate="txtEmail"></asp:RequiredFieldValidator>
    <br />
    <asp:Label runat="server">Subject:</asp:Label>
    <asp:TextBox ID="txtSubject" runat="server"></asp:TextBox>
    <asp:RequiredFieldValidator runat="server" ErrorMessage="Please enter the information requested." ControlToValidate="txtSubject"></asp:RequiredFieldValidator>
    <br />
    <asp:Label runat="server">Message:</asp:Label>
    <textarea runat="server" id="txtMessage" rows="7" cols="24"></textarea>
    <asp:RequiredFieldValidator runat="server" ErrorMessage="Please enter a message." ControlToValidate="txtMessage"></asp:RequiredFieldValidator>
    <br />
    <asp:Button runat="server" ID="btnSend" onclick="btnSend_Click" Text="Send" />
    <asp:Button runat="server" ID="btnReset" onclick="btnReset_Click" Text="Reset" />
</asp:Panel>



Do you think that that is enough to have a complete contact form? Well, to be honest, it is, however, two errors can still occur:
  • When the user presses the reset button, it will cause validation.
  • The user can still enter an invalid email address

Luckily, both of these are easy to fix. In the reset button, add this piece of info to it:
CausesValidation=”false”


We have then fixed the problem with causing validation when trying to reset the forms. Now to fix our other problem, the validation of the email that has been entered by the user. This is also easy, but requires that you know how to manipulate regular expressions. For this, we will be using another of ASP.NET’s validation server controls, the Regular Expression Validator control. This takes a regular expression and checks it against the text entered in the textbox. Place this line of code underneath the RequiredFieldValidator control that checks the email field:
<asp:RegularExpressionValidator runat=”server” ErrorMessage=”Please enter a valid email address.” ControlToValidate=”txtEmail” ValidationExpression=”\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*”></asp:RegularExpressionValidator>



The code should then look like this:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Email Form.ascx.cs" Inherits="Email_Form.EmailForm" %>
<%@ Import Namespace="System.Net.Mail" %>
<%@ Import Namespace="System.Net" %>
<script runat="server" type="text/C#">
    public void btnSend_Click(object sender, EventArgs e){
        MailMessage msg = new MailMessage();
        msg.To.Add(new MailAddress("Your email"));
        msg.From = new MailAddress(txtEmail.Text);
        msg.Subject = txtSubject.Text;
        msg.Body = txtName.Text + Environment.NewLine + txtMessage.Value;
        SmtpClient client = new SmtpClient();
        client.Host = "Your host";
        client.Port = 25;
        NetworkCredential cred = new NetworkCredential("Your username”,Your password”);
        client.Credentials = cred;
        client.EnableSsl = true;
        client.Send(msg);
    }
    public void btnReset_Click(object sender, EventArgs e)
    {
        txtName.Text = "";
        txtEmail.Text = "";
        txtSubject.Text = "";
        txtMessage.Value = "";
    }
</script>
<asp:Panel runat="server" style="margin-bottom: 32px">
    <asp:Label runat="server">Name:</asp:Label>
    <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
    <asp:RequiredFieldValidator runat="server" ErrorMessage="Please enter the information requested." ControlToValidate="txtName"></asp:RequiredFieldValidator>
    <br />
    <asp:Label runat="server">Email:</asp:Label>
    <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
    <asp:RequiredFieldValidator runat="server" ErrorMessage="Please enter the information requested." ControlToValidate="txtEmail"></asp:RequiredFieldValidator>
    <asp:RegularExpressionValidator runat="server" ErrorMessage="Please enter a valid email address." ControlToValidate="txtEmail" ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
    <br />
    <asp:Label runat="server">Subject:</asp:Label>
    <asp:TextBox ID="txtSubject" runat="server"></asp:TextBox>
    <asp:RequiredFieldValidator runat="server" ErrorMessage="Please enter the information requested." ControlToValidate="txtSubject"></asp:RequiredFieldValidator>
    <br />
    <asp:Label runat="server">Message:</asp:Label>
    <textarea runat="server" id="txtMessage" rows="7" cols="24"></textarea>
    <asp:RequiredFieldValidator runat="server" ErrorMessage="Please enter a message." ControlToValidate="txtMessage"></asp:RequiredFieldValidator>
    <br />
    <asp:Button runat="server" ID="btnSend" onclick="btnSend_Click" Text="Send" />
    <asp:Button runat="server" ID="btnReset" CausesValidation="false" onclick="btnReset_Click" Text="Reset" />
</asp:Panel>



Now we have a working contact form. It is useable in all ASP.NET websites.

Step 4 – Testing the Contact Form
We know that it should work, but does it really? That is something that we, programmers, should always be asking ourselves. The only way for us to answer that question is to test it ourselves. That way we make sure it works, and we don’t make our users unhappy. To test our contact form that we have just created, select the “Project” menu in the main menu and then “Add New Item” and select “Web Form” then press “OK”. A page that looks like:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Email_Form.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>


will appear. This is the basic ASP.NET page that we will be using to test our Contact Form. Add this line of code underneath the line introducing the page:
<%@ Register TagName="EmailForm" Src="~/Email Form.ascx" TagPrefix="cc" %>


This creates the tag <cc:EmailForm runat=”server” /> that is our contact field. Now, place our new tag into the <div> that is inside the form. The code should then look like this:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Email_Form.WebForm1" %>
<%@ Register TagName="EmailForm" Src="~/Email Form.ascx" TagPrefix="cc" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <cc:EmailForm ID="EmailForm1" runat="server" />
    </div>
    </form>
</body>
</html>


Now, we are able to test our contact form. Select the WebForm1.aspx file if you haven’t and either hit the green arrow key or press F5 to start testing. Do what you want to test, and then close out of it. You now have a working contact form that you can use in any ASP.NET website.

Here is the sample that was created using this tutorial available for download if you think you didn’t do it right: Attached File  Contact Form.zip (17.46K)
Number of downloads: 1748

Other things:
It is possible to further customize the contact form, but I won’t go into that here. To do that, you can either use the code behind file or just customize how it looks using CSS.

References:
One thing that I found useful while writing this was a tutorial itself on the ASP.NET validation server controls, it can be found here.
Another great site is Microsoft’s MSDN, found here.

Is This A Good Question/Topic? 0
  • +

Page 1 of 1