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
    {
        [Required]
        [StringLength(50)]
        [Display(Name = "First Name")]
        public string firstName { get; set; }
        [Required]
        [StringLength(50)]
        [Display(Name = "Last Name")]
        public string lastName { get; set; }
        [Required]
        [StringLength(60)]
        [EmailAddress]
        [Display(Name = "Email Address")]
        public string email { get; set; }
        [StringLength(50)]       
        [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"))
                {
                    Html.AntiForgeryToken();
                    <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>
                    <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>
                    <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>
                    <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>
                    <div class="form-group">
                        <label asp-for="comment" class="control-label">Comment</label>
                        <textarea asp-for="comment" rows="5" class="form-control"></textarea>
                    </div>
                    <button type="submit" class="btn btn-default">Submit</button>
                     }
                        </div>

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.

   [Route("contact")]
        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.


 [HttpPost]
        [ValidateAntiForgeryToken]
        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");
            mailMessage.To.Add(contact.email);
            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>");
            s.Append(contact.comment);
            mailMessage.Body = s.ToString();
            mailMessage.Subject = "New message from contact form";
            client.Send(mailMessage);

            //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);
                conn.Open();
                cmd.ExecuteNonQuery();
                conn.Close();

            // 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 *