A Simple MVC Preview 3 Contact Form, Custom HtmlHelper and Model Example

I have just recently designed a site for a client and decided to use MVC for it.  I think above all the best thing I enjoy about it, is the clean markup that is outputted.  Of course I also have great administration for the work and effort that has gone into the actual framework, it is superb!  So what I wanted to share with this post is simply how easy it is to create a contact form for your website.  We will include 4 fields, being Full name, Telephone, Email Address and Enquiry.  So to encapsulate everything we need here I will bullet these out:

  • An action for the contact form
  • A model which encapsulates and describes an enquiry
  • A custom HTML Helper Extension Method
    • I created this because if you want to add the class attribute to an input using the provided helper method, you have to use upper case C of the class attribute.  My only issue with this is that if you design to XHTML Strict it is not valid.  So a custom helper method.
  • A View for the contact page
  • A View for the thank you page

 

An action for the contact form

This is the action which we will use as the action attribute for our form.  You will see I create an instance of our enquiry model, and after sending the email I forward this model onto the thank you view.  You need to include the using statement for System.Net.Mail

Hide Code [-]
        public ActionResult SendContactForm(string Name, string Telephone, string Email, string Enquiry)
        {
            Models.Enquiry enq = new MvcApplication.Models.Enquiry(Name, Telephone, Email, Enquiry);

            MailAddress addressTo = new MailAddress("email@awebsite.co.uk");
            MailAddress addressFrom = new MailAddress("noreply@anotherwebsite.co.uk");

            MailMessage message = new MailMessage(addressFrom, addressTo);

            message.Subject = "Website Enquiry";
            System.Text.StringBuilder sb1 = new System.Text.StringBuilder();
            sb1.AppendLine(String.Format("<p><span style='float:left;width:200px;font-weight:bold;display:block;'>Name</span> : {0}</p>", Name));
            sb1.AppendLine(String.Format("<p><span style='float:left;width:200px;font-weight:bold;display:block;'>Telephone Number</span> : {0}</p>", Telephone));
            sb1.AppendLine(String.Format("<p><span style='float:left;width:200px;font-weight:bold;display:block;'>Email</span> : {0}</p>", Email));
            sb1.AppendLine(String.Format("<p><span style='float:left;width:200px;font-weight:bold;display:block;'>Enquiry</span> : {0}</p>", Enquiry));
            message.IsBodyHtml = true;
            message.Body = sb1.ToString();
            SmtpClient s = new SmtpClient("127.0.0.1", 25);

            s.Send(message);

            return View("Thankyou", enq);
        }
{..} Click Show Code

 

A model which encapsulates and describes an enquiry

In the above code sample you can see the class, Models.Enquiry.  That is our model and the simple code for it is below.  Nothing special but does the job.

Hide Code [-]
namespace MvcApplication.Models
{
    public class Enquiry
    {
        private string m_name;

        public string Name
        {
            get { return m_name; }
            set { m_name = value; }
        }
        private string m_telephoneNumber;

        public string TelephoneNumber
        {
            get { return m_telephoneNumber; }
            set { m_telephoneNumber = value; }
        }
        private string m_email;

        public string Email
        {
            get { return m_email; }
            set { m_email = value; }
        }
        private string m_enquiry;

        public string Enquiry1
        {
            get { return m_enquiry; }
            set { m_enquiry = value; }
        }

        public Enquiry(string name,
            string telephoneNumber,
            string email,
            string enquiry)
        {
            m_name = name;
            m_telephoneNumber = telephoneNumber;
            m_email = email;
            m_enquiry = enquiry;
        }
    }
}
{..} Click Show Code

 

A custom HTML Helper Extension Method

This was due to me experiencing the rendering of the input tag with upper case "C" of the class attribute.  If you try and construct the input Html Helper with new {class="YourClass"} the compiler thinks you are actually creating a class object and not a variable.  So you have to use new {Class="YourClass"} .  This works, and it renders correctly in HTML, but as I said above, this is not valid for XHTML Strict.  So I simply made use of the .NET 3.5 framework and created an extension method for this.

Hide Code [-]
        public static string TextBoxWithClass(this System.Web.Mvc.HtmlHelper helper,string name, string CssClass)
        {
            string format = "<input type=\"text\" name=\"{0}\" class=\"{1}\" id=\"{0}\" value=\"\" />";
            format = String.Format(format,name, CssClass);
            return format;
        }
{..} Click Show Code

 

I will then use the above inside the form which I will show next.

 

A View for the contact page

So you will see below, I want to assign the class name of WithBorder to each TextBox.  One thing which I will mention, is that inside the Markup for the view I have included the following line so that my extension methods are seen.  Notice the action attribute in the form.  As usual you can use either POST or GET as the method for your form.  I prefer POST simply because I don't want the contents of the Request.Form key value pairs inside the URL.

Hide Code [-]
<%@ Import Namespace="MvcApplication.Classes" %>
{..} Click Show Code

 

Hide Code [-]
    <div id="GeneralEnquiry" class="enquiryForm">
        <form action="/Home/SendContactForm" method="post">
        <p>
            <span>Name</span>
            <%= Html.TextBoxWithClass("Name","WithBorder") %>
        </p>
        <p>
            <span>Telephone Number</span>
            <%= Html.TextBoxWithClass("Telephone", "WithBorder")%>
        </p>
        <p>
            <span>Email Address</span>
            <%=  Html.TextBoxWithClass("Email", "WithBorder")%>
        </p>
        <p>
            Enquiry</p>
        <p>
            <%= Html.TextAreaWithClass("Enquiry","WithBorder")%>
        </p>
        <p>
            <%=Html.SubmitButton("btnSubmit", "Send Enquiry")%>
        </p>
        </form>
    </div>
{..} Click Show Code

 

A View for the thank you page

Finally you need a view for your thank you page which you render inside the action for the contact script.  I have not used the Model which I forward to the page, but in essence a scenario would be you could confirm with the client the actual details of what they sent you in the form.

Hide Code [-]
    <h2>
        Thank you for your enquiry</h2>
    <p>
        Your enquiry has been sent, we will reply to your enquiry as soon as possible. Thank you.</p>
        
        If I used the Model I could access like this:
        <ul>
            <li>Name : <%= ViewData.Model.Name %></li>
            <li>Telephone Number : <%= ViewData.Model.TelephoneNumber %></li>
            <li>Email : <%= ViewData.Model.Email %></li>
        </ul>
{..} Click Show Code

 

Cheers for now,

 

Andrew :-)

Published Thursday, June 05, 2008 9:32 AM by REA_ANDREW

Comments

# A Simple MVC Preview 3 Contact Form, Custom HtmlHelper and Model Example - Andrew Rea

Pingback from  A Simple MVC Preview 3 Contact Form, Custom HtmlHelper and Model Example - Andrew Rea

# re: A Simple MVC Preview 3 Contact Form, Custom HtmlHelper and Model Example

Thursday, June 05, 2008 6:15 AM by Trevor

I believe {_class="YourClass"} works and produces valid XHTML.  Anyway, nice sample.

# re: A Simple MVC Preview 3 Contact Form, Custom HtmlHelper and Model Example

Thursday, June 05, 2008 3:00 PM by Eric

Would you Enquiry class be a good candidate for automatic properties and also leverage Object Initializers to eliminate that greedy constructor?

# Interesting Finds: 2008.06.06

Thursday, June 05, 2008 6:55 PM by gOODiDEA.NET

Debug Setting .NET breakpoints in Windbg for applications that crash on startup Web Javascript HTML Construction

# re: A Simple MVC Preview 3 Contact Form, Custom HtmlHelper and Model Example

Thursday, June 05, 2008 7:52 PM by itsmecurtis

FYI: You can use a reserved keyword in C# (such as class) by prepending @.  So, you can get the input tag you want using the built-in helper if you pass into Html.TextBox's htmlAttributes parameter: new { @class = "YourClass" }

The compiler no longer thinks you're trying to create a new class and the resulting XHTML attribute is properly cased.

# Link Listing - June 5, 2008

Friday, June 06, 2008 8:37 AM by Christopher Steen

Link Listing - June 5, 2008

# re: A Simple MVC Preview 3 Contact Form, Custom HtmlHelper and Model Example

Friday, June 06, 2008 12:53 PM by REA_ANDREW

itsmecurtis : Great Tip, much apreciated!  

I use that notation say when I want to create an unescaped string, but never knew I could use it in such context. Again, thanks for your input! :-)

Top Tip.

# re: A Simple MVC Preview 3 Contact Form, Custom HtmlHelper and Model Example

Saturday, June 07, 2008 5:49 AM by REA_ANDREW

Eric : I will definately look into them, thanks for the comment

# re: A Simple MVC Preview 3 Contact Form, Custom HtmlHelper and Model Example

Tuesday, June 24, 2008 7:34 AM by sandy

How to create DropDownList onchange event in MVC

# ASP.NET MVC Archived Buzz, Page 1

Friday, July 11, 2008 11:18 AM by ASP.NET MVC Archived Buzz, Page 1

Pingback from  ASP.NET MVC Archived Buzz, Page 1

Leave a Comment

(required) 
(required) 
(optional)
(required)