AJAX HTML Editor based Contact Form inside UpdatePanel along with UpdateProgress

 

In this tutorial, we see how to develop a simple Contact Page webform. This Contact Page is going to be a similar one to what we usually see in our day to day experience out in internet. Here we use AJAX HTML editor to enable Html email to the owner of the website. The basic outline would be – Users provide their general details like name and email, and also they can provide Html Message (using AJAX HTML Editor) in the Contact Page, where a basic validation is done as first step. Then we take the Html string, and send the same in the email to the authorized person of the website (typically owner) using SMTP settings (System.Net.Mail namespace). For ease of use, we use Gmail SMTP settings (host and port) for sending email. For better interactivity UpdateProgress control is used to show the progress of email routine.

================================================================================================

ContactPage Website

Create a sample ‘ContactPage’ website in VS 2010.

================================================================================================

  1. Open Vs 2010 –> File –> New –> Website.
  2. select –> C#
  3. Select ‘Asp.Net Empty Website’ –> name – ‘ContactPage’.

================================================================================================

Adding AJAX Control Toolkit to Website

To use AJAX HTML Editor – first download the AJAX control toolkit and make a reference of it in website.

================================================================================================

  1. Download AJAX Control ToolKit – AJAX Control Toolkit from CodePlex – AjaxControlToolkit.Binary.NET4.zip.
  2. Once downloaded, extract the content of zip file to a folder.
  3. Go to the Website in the Solution Explorer of VS 2010 –> Right click the Project node –> Select ‘Add Reference…’ –> In the add reference dialog, select ‘Browse’ tab –> Navigate to the folder (where the extracted content resides), and select ‘AjaxControlToolkit.dll’ –> Press OK.
  4. Thats it, now a reference to AJAX Control ToolKit has been added to the project.
  5. After adding reference, Bin folder of ContactPage website should like below in the Solution Explorer.

AJAXHTMLEditorContactForm-BinStructure

================================================================================================

Email.cs

This class holds the code to send email with the data provided in the contact form.

================================================================================================

  1. Right Click ‘ContactPage’ in Solution explorer of VS 2010.
  2. Select ‘Add Asp.Net Folder…’ –> App_code.
  3. Add Email.cs (Right Click App_Code folder in Solution Explorer –> Add New Item –> Class).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Mail;
using System.Configuration;

public class Email
{
    public string subject { get; set; }
    public string fromEmail { get; set; }
    public string fromName { get; set; }
    public string messageBody { get; set; }

    public string SendEmail()
    {
        try
        {
            MailMessage Message = new MailMessage();
            Message.IsBodyHtml = true;

            Message.To.Add
                (
                new MailAddress
                    (
                    ConfigurationManager.AppSettings["toEmail"].ToString(),
                    ConfigurationManager.AppSettings["toName"].ToString()
                    )
                 );

            Message.From = new MailAddress(this.fromEmail, this.fromName);
            Message.Subject = this.subject;
            Message.Body = this.messageBody;
            Message.ReplyToList.Add(this.fromEmail);

            SmtpClient sc = new SmtpClient();
            
            sc.EnableSsl = true;

            sc.Send(Message);
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
        return "email sent Successfully!!!";
    }
}

================================================================================================

web.config SMTP Settings

Incorporate the necessary SMTP settings (required to send email) in web.config file.

================================================================================================

<?xml version="1.0"?>
<configuration>
    <appSettings>
      <add key="toEmail" value="to@gmail.com"/>
      <add key="toName" value="Give To Name"/>
    </appSettings>
  
    <system.web>
        <compilation debug="false" targetFramework="4.0" />
    </system.web>
  
    <system.net>
      <mailSettings>
        <smtp>
          <network
               host="smtp.gmail.com"
               port="587"
               userName="example@gmail.com"
               password="examplePassword" />
        </smtp>
      </mailSettings>
    </system.net>
  
</configuration>

================================================================================================

Default.aspx

This is the page which holds the UI for Contact Page along with validation.

================================================================================================

<%@ Page Language="C#" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit.HTMLEditor" TagPrefix="cc1" %>

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

<script runat="server">
    protected void btnMessage_Click(object sender, EventArgs e)
    {
        Email email = new Email();
        
        email.fromEmail = txtEmail.Text;
        email.fromName = txtName.Text;
        if (!String.IsNullOrEmpty(txtSubject.Text))
            email.subject = txtSubject.Text;
        else
            email.subject = "Message from " + txtEmail.Text;
        email.messageBody = edtrMessage.Content.ToString() + "<br/>" + txtName.Text +
                            "<br/>" + txtEmail.Text;

        string success = "";
        success = email.SendEmail();

        lblSuccessMessage.Text = success;
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function Call() {
            return Page_ClientValidate();
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>

        <asp:UpdatePanel ID="updtPnlContactForm" runat="server">
            <ContentTemplate>
                <table style="width: 500px">
                    <tr>
                        <td>
                            <asp:Label 
                                ID="lblName" 
                                runat="server" 
                                Text="Name">
                            </asp:Label>
                        </td>
                        <td>
                            <asp:TextBox 
                                ID="txtName" 
                                runat="server">
                            </asp:TextBox>
                            <asp:RequiredFieldValidator 
                                ID="rfvName" 
                                runat="server" 
                                ErrorMessage="*"
                                ControlToValidate="txtName">
                            </asp:RequiredFieldValidator>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <asp:Label 
                                ID="lblEmail" 
                                runat="server" 
                                Text="Email">
                            </asp:Label>
                        </td>
                        <td>
                            <asp:TextBox 
                                ID="txtEmail" 
                                runat="server">
                            </asp:TextBox>
                            <asp:RegularExpressionValidator 
                                id="valRegEx" 
                                runat="server"
                                ControlToValidate="txtEmail"
                                ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
                                ErrorMessage="*Invalid Email address."
                                display="dynamic">
                            </asp:RegularExpressionValidator>
                            <asp:RequiredFieldValidator 
                                ID="rfvEmail" 
                                runat="server" 
                                ErrorMessage="*"
                                ControlToValidate="txtEmail">
                            </asp:RequiredFieldValidator>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <asp:Label 
                                ID="lblSubject" 
                                runat="server" 
                                Text="Subject">
                            </asp:Label>
                        </td>
                        <td>
                            <asp:TextBox 
                                ID="txtSubject" 
                                runat="server">
                            </asp:TextBox>
                        </td>
                    </tr>
                    <tr>
                        <td valign="top">
                            <asp:Label 
                                ID="lblMessage" 
                                runat="server" 
                                Text="Message">
                            </asp:Label>
                        </td>
                        <td>
                            <cc1:Editor 
                                ID="edtrMessage" 
                                runat="server" 
                                Width="500px" 
                                Height="300px" />
                            <asp:RequiredFieldValidator 
                                ControlToValidate="edtrMessage" 
                                ID="rfvMessage" 
                                runat="server"
                                ErrorMessage="Write a Message">
                            </asp:RequiredFieldValidator>
                        </td>
                    </tr>
                    <tr>
                        <td>
                        </td>
                        <td>
                            <asp:Button 
                                ID="btnMessage" 
                                runat="server" 
                                Text="Submit Message"
                                OnClick="btnMessage_Click" 
                                OnClientClick="return Call()" />
                            <asp:UpdateProgress 
                                ID="updtPrgrssEmail" 
                                runat="server">
                                    <ProgressTemplate>
                                        <img alt="Loading..." src="images/loading.gif" />
                                    </ProgressTemplate>
                            </asp:UpdateProgress>
                        </td>
                    </tr>
                    <tr>
                        <td>
                        </td>
                        <td>
                            <asp:Label 
                                ID="lblSuccessMessage" 
                                runat="server" 
                                Text="">
                             </asp:Label>
                        </td>
                    </tr>
                </table>
            </ContentTemplate>
        </asp:UpdatePanel>
    </div>
    </form>
</body>
</html>

================================================================================================

Folder Structure

The complete Solution Explorer structure of ‘ContactPage’ website.

================================================================================================

AJAXHTMLEditorContactForm-FolderStructure

================================================================================================

OUTPUT

================================================================================================

Sending Email ->

AJAXHTMLEditorContactForm-SendingEmail

Sent Email ->

 AJAXHTMLEditorContatPage-EmailSent

NOTE :-
  1. Validation of user input can be done in a much better way. We can parse the Html strings which are submitted by user and only can display the content which is not harmful (as a malicious user can send <script> tags as an attack). So we can think of using HtmlAgilityPack or even Regular Expressions to parse the content and then display it to the user.

  2. I never narrated the flow of code in this article, it can be better understood if the same is debugged with break points.

  3. Download the loading.gif – Click Here, it is used along with UpdateProgress Control.

  4. Make sure the SMTP settings are correct, or else there will be SMTP exceptions.

Disclaimer:

All coding and suggestions made in the above discussion is strictly in point of view of the author. It is neither mentioned any where nor even concluded that this is the only possible way to go with, as there will be always a chance for a new approach in achieving the same requirement (in context of programming). The above mentioned code is strictly written and explained for the sake of new comers to C# and ASP.NET world.

You may also like...

  • Jesse

    Hi, can you send me the files, I can’t get the project to work.

    Thanks,

  • Sara

    Hey thanks rami, the code, is explained in very well manner.. :)

  • Sara

    Hey Thanks Rami, code is explained in very good manner :)

  • andy

    Hi

  • mahesh

    Ya it Good.

  • christian louboutin sale

    Your content is very appealing to me, I later will often focus on your dynamic

  • rahmo

    hello
    I tried this code but for some reason it says falure to send message

    just to make sure the feild that i need to change that are in the web config in the network tag only ?
    my email and password ?

    thank you

  • RamiVemula

    @Rahmo – you need to change appsettings also. If still you face the problems, then you got to check the smtp details.

  • rahmo

    @remi – thx for yr reply … well yes the app section as well i changed but still not workin i traced it and it always jump to the exception after sc.Send(Message);

    here’s my web config – if there’s anything wrong

    thank you in advance for the nice article

  • rahmo

    configuration

    configuration

  • rahmo

    configuration
    appSettings
    add key=”toEmail” value=”the.rahmony@gmail.com”
    add key=”toName” value=”a name”
    appSettings
    system.web
    <ompilation debug="true" targetFramework="4.0"
    httpRuntime requestValidationMode="2.0"
    system.web
    system.net
    mailSettings
    smtp
    network host="smtp.gmail.com" port="465" userName="the.rahmony@gmail.com" password=""
    smtp
    mailSettings
    system.net
    configuration

  • rahmo

    It works now … thank you very much :)

  • RamiVemula

    @Rahmo – Whats the problem you faced and how did you solved it. If you post that info, it will solve other readers problem, if they faced the same.