A contact form for ASP.NET 2.0

How to create a contact form in ASP.Net 2.0

Here is a complete Step by Step example of creating a contact form for use in ASP.Net 2.0.

Create the model

First create a model in the Models folder called contact.cs. This model uses data annotation to validate the fields in the model. For example the first name is required and should not be longer than 50 characters.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace myNamespace.Models
    public class Contact
        [Display(Name = "First Name")]
        public string firstName { get; set; }
        [Display(Name = "Last Name")]
        public string lastName { get; set; }
        [Display(Name = "Email Address")]
        public string email { get; set; }
        [RegularExpression("^(?!0+$)(\\+\\d{1,3}[- ]?)?(?!0+$)\\d{10,15}$",ErrorMessage="Enter a valid Phone Number.")]
        [Display(Name = "Phone Number")]
        public string phone { get; set; }
        public string comment { get; set; }

Create a Sql Server table with corresponding fields where the data will be stored. Be sure to add an additional date field which will automatically store a time stamp for the record.

Create the view

Next create view which we will call contact.cshtml. This view will present the form. It uses bootstrap 3 classes and also makes use of ASP.Net built-in tag helpers. For example, the Validation Message tag helper allows me to add to the span tag the code asp-validation-for that is used to display the error when the validation fails. Notice that the target of the form is “GetForm” in the “Home” controller.

   <div class="well">

                            @model myNamespace.Models.Contact
                            @using (Html.BeginForm("GetForm", "Home"))
                    <div class="form-group">
                        <label asp-for="firstName" class="control-label">First Name</label>
                        <input asp-for="firstName" class="form-control" />
                        <span asp-validation-for="firstName" class="text-danger"></span>
                    <div class="form-group">
                        <label asp-for="lastName" class="control-label">Last Name</label>
                        <input asp-for="lastName" class="form-control" />
                        <span asp-validation-for="lastName" class="text-danger"></span>

                    <div class="form-group">
                        <label asp-for="email" class="control-label">Email</label>
                        <input asp-for="email" class="form-control" />
                        <span asp-validation-for="email" class="text-danger"></span>
                    <div class="form-group">
                        <label asp-for="phone" class="control-label">Phone</label>
                        <input asp-for="phone" class="form-control" />
                        <span asp-validation-for="phone" class="text-danger"></span>
                    <div class="form-group">
                        <label asp-for="comment" class="control-label">Comment</label>
                        <textarea asp-for="comment" rows="5" class="form-control"></textarea>
                    <button type="submit" class="btn btn-default">Submit</button>

Modify the Controller

At the top of the controller, be sure to add.

using myNamespace.Models;
using System.Net.Mail;
using System.Data.SqlClient;
using System.Net;

Add the code to open the contact form.

        public IActionResult contact()
            ViewData["Title"] = "Contact Us";
            return View();

Next add the code to process the submit. GetForm was the target of the post for the form.

        public IActionResult GetForm([FromForm] Contact contact)
            // send yourself an email that the contact form had been filled out.
            SmtpClient client = new SmtpClient("mail.yoursite.com");
            client.UseDefaultCredentials = false;
            client.Credentials = new NetworkCredential("info@yoursite.com", "abc");

            MailMessage mailMessage = new MailMessage();
            mailMessage.IsBodyHtml = true;
            mailMessage.From = new MailAddress("info@yoursite.com");
            System.Text.StringBuilder s = new System.Text.StringBuilder();
            s.Append(contact.firstName + " " + contact.lastName + "<br>");
            s.Append(contact.email + "<br>");
            s.Append(contact.phone + "<br>");
            mailMessage.Body = s.ToString();
            mailMessage.Subject = "New message from contact form";

            //connect to database            
            String connString = "Data Source = xxxx"; //include your connection string to your database            
            SqlConnection conn = new SqlConnection(connString);

            // build sql insert command   
            System.Text.StringBuilder s1 = new System.Text.StringBuilder();
            s1.Append("insert contacts (firstname,lastname, email,phone, comment)");
            s1.Append("values ('" + contact.firstName + "', '" + contact.lastName + "','");
            s1.Append(contact.email + "','" + contact.phone + "','" + contact.comment +"')");
            String cmdString = s1.ToString();

            //insert record into database
            SqlCommand cmd = new SqlCommand(cmdString, conn);

            // redirect to a thank you page.
            ViewData["Message"] = "Thank you for your interest. We will contact you.";
            ViewData["Title"] = "Thank you";
            return RedirectToAction("thankyou");

Be sure you have also created a Thank you page for this to redirect to.

Leave a Reply

Your email address will not be published. Required fields are marked *