Building a contact form in ASP.NET with C#

by Dave Reeder 17. January 2010 00:02

As a busy Designer, I tend to leave forms and server side code to Developers, but even small sites normally require a contact us form.

In the old days, one would put a mailto: link to your email address. However, this will normally lead to spam bots getting hold of the email and spamming it like crazy, and/or it will launch Outlook (or some other email application you have set as default) which isn't really a great thing as lot's of people use Hotmail, Yahoo or some other Web Mail instead.

The answer is normall an email form, but to successfully send this we need not only the form, but some sort of server side code to process it and deliver the message.

I am quite a fan of ASP.NET as my server supports it (as I share my server with Alex, a friend who is an ASP.NET Developer) and I like all the friendly "Designer" features that the Visual Studio IDE has to offer.

To use this form in our ASP.NET web site we use the following controls in our HTML contact page (contact.aspx):

<form method="post" action="">
  <ul class="lstContact">
    <li class="labelContainer">
    <asp:Label ID="confirmMessage" runat="server" Text="Thank you, your message has been sent!" Visible="false">
    </asp:Label></li>
    <li><asp:textbox runat="server" id="Name" Text="name" /></li>
    <li><asp:textbox runat="server" id="txtEmail" Text="email" /></li>
    <li><asp:textbox runat="server" id="Subject" Text="subject" /></li>                 
    <li><asp:textbox id="txtMessage" runat="server" Text="message" textmode="multiline" /></li> 
    <li><asp:button id="cmdSend" runat="server" /></li>
  </ul>
</form>

Note, I have set the form out in a list which makes it easier to lay out, especially if we add labels which we can float left and float their corresponding input/textarea to the right.
We are going to show the label (confirmMessage) when the user clicks send and the form has finished sending the email. So to begin with, this label is set to Visible="false".

Because this is ASP.NET, we don't need an onclick event on the send button, we will attach an event handler in the C# code-behind file (contact.aspx.cs):

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net.Mail;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        this.cmdSend.Click += new EventHandler(cmdSend_Click);
    }

    //Will be called when button has been clicked
    public void cmdSend_Click(object sender, EventArgs e)
    {

        //Call send email function
        Send(txtMessage.Text, txtEmail.Text, "youaddress@yourdomain.co.uk", "Email from />www.yourdomain.co.uk");
        confirmMessage.Visible = true;
    }

    public static string Send(string Message, string EmailFrom, string EmailTo, string Subject)
    {
        System.Net.Mail.MailMessage objMessage = new System.Net.Mail.MailMessage(EmailFrom, EmailTo);
        SmtpClient objClient = new SmtpClient();
        objMessage.IsBodyHtml = true;
        objMessage.Subject = "" + Subject;
        objMessage.Body = "" + Message;

        //This is the mail server ip
        objClient.Host = "0.0.0.0";         
        try
        {
            objClient.Send(objMessage);
            return "";
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }
}


This is the complete code-behind file so you can see the namespaces used etc.

So, when the page loads we attach out event handler to watch out for the user clicking our Send button, which has the ID of "cmdSend". When the send button is clicked, the code sends the message and users email address to the specified email address and with the specified subject so you know it is a genuine email from your web site.
It also show the confirmation message label so the web site visitor knows the email has been sent.

It doesn't send if the email and message fields are left blank.

Hope this helps! Please note, I am only publishing relevant coments on this topic.

Tags: , , , , , , ,

Comments

1/19/2010 4:13:19 AM #

Thank you for posting such a useful website. Your weblog happens to be not just informative but also very stimulating too. There are a limited number of people who are capable of write technical articles that creatively. we are on the lookout for information regarding this topic. We ourselves went through several websites to find knowledge with regard to this.I will keep coming back !!

official fighter ratings list

1/27/2010 4:06:04 AM #

wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post


Regards
Clark

Kontes SEO bisnis syariah online produk herbal PT.Exer Indonesia rekomendasi MUI

1/27/2010 11:08:03 AM #

I found your blog on Google and read a few of your other posts. I just added you to my Google News Reader. Keep up the good work. Look forward to reading more from you in the future.

sikat ang pinoy

1/28/2010 5:11:03 AM #

Very nice,..
I like your Oppinion

regards

Write Hype

1/28/2010 8:06:31 PM #

This new technology is known as Asp.net. Asp.net allows the developer to build applications faster. In this we can do the coding either by using any of the languages like Visual Basic,c#,Java script. But I always feel comfortable with C# coding.

Bryan Nash

1/30/2010 12:13:09 PM #

I like blogengine.net powered by asp.net it is good for blog commenting it bring huge of backlinks and traffic.

sikat ang pinoy

1/30/2010 3:37:37 PM #

Great breakdown Dave, I usually just use a template as my coding skills non-existant.  D: Great post!

equipment financing

1/31/2010 4:56:47 AM #

elegant solution, Dave.

Valentine

2/9/2010 8:22:52 AM #

Nice form..

accident attorney

2/9/2010 11:53:55 PM #

hey man great work....i just have a small problem the name of our controller class for working with contacts is named the HomeController class. Shouldn’t the controller be named ContactController?

app developer guide

2/12/2010 10:24:32 AM #

Admiring the time and effort you put into your blog and detailed information you offer! I will bookmark your blog and have my friends also check up here often. Thumbs up!

Sikat ang pinoy

2/13/2010 5:27:33 PM #

Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and I hope you post again soon

SEO Blog

2/16/2010 1:14:33 AM #

Dang admin you have got a few wierd error codes on your blog that says parse error unexpected T String in line 19

Leeanne Gummer

Comments are closed