Please disable your adblock and script blockers to view this page
 

Create contact us form/page and Ajax HtmlEditorExtender control to format textbox text and send formatted text in email in asp.net

Introduction: In this article I will explain with example How to create Contact Us form/page and send the inquiry details by email in asp.net using C# and VB.Net.  Also I have used the HtmlEditorExtender control of Ajax so that visitors can format their comments/message/feedback and send formatted comments to the admin of the website.
Contact Us form and use of Ajax HtmlEditorExtender control in asp.net
Click on image to view clear enlarged demo
 
Description: So basically through this article you will learn the following
  • How to create contact us page/form in asp.net
  • How to format the text in text box using Ajax’s HtmlEditorExtender control and send formatted text in email.
  • How to send email in asp.net using Gmail credentials.
In previous articles i explained How to create Login page/form and check username,password in asp.net using sql server database and Create Change password form/page in asp.net using Sql server and Encrypt and decrypt username,password and store in Sql Server database and Recover and reset the forgot password using activation link in email id  and Ajax TabContainer example to create multiple tabs/panels and Ajax CascadingDropDown fill DropDownList with Countries,states and cities

Implementation: Let’s create a Contact Us page to better understand. 

HTML Source Code:
  • Add a page and name it “ContactUs.aspx” and in the <Form> tag of this design page (ContactUs.aspx) Place 4 TextBox controls, a Label and a Button controls from the standard category and place  ScriptManager from the AJAX Extension category of the visual studio toolbox. Also place HtmlEditorExtender control of Ajax from the installed AjaxControlToolkit.
  • If you have not installed and don’t know how to install Ajax control toolkit then read the article How to install Ajax Control Toolkit in Visual Studio? 

<div>
    <fieldset style="width:510px;">
    <legend>Contact Us form Example</legend>
   
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
    <table>
    <tr><td colspan="2">All the fields are mandatory</td></tr>
    <tr>
    <td>Name: *</td><td>
        <asp:TextBox ID="txtName" placeholder="Your Name Here" runat="server"
            Width="220px"></asp:TextBox>
        <asp:RequiredFieldValidator ID="rfvName" runat="server"
            ErrorMessage="Please enter your name" ControlToValidate="txtName"
            Display="Dynamic" ForeColor="Red" SetFocusOnError="True"></asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
    <td>Email * </td><td>
        <asp:TextBox ID="txtEmail" placeholder="Your Email Address Here" runat="server"
            Width="220px"></asp:TextBox>
        <asp:RequiredFieldValidator ID="rfvEmailId" runat="server"
            ErrorMessage="Please enter email address" ControlToValidate="txtEmail"
            Display="Dynamic" ForeColor="Red" SetFocusOnError="True"></asp:RequiredFieldValidator><br />
        <asp:RegularExpressionValidator ID="rgeEmailId" runat="server"
            ErrorMessage="Please enter valid email address"
            ControlToValidate="txtEmail" Display="Dynamic" ForeColor="Red"
            SetFocusOnError="True"
            ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
        </td>
    </tr>
    <tr>
    <td>Contact No. * </td><td>
        <asp:TextBox ID="txtContact" placeholder="Your Contact No. Here" runat="server"
            Height="22px" Width="220px"></asp:TextBox>
        <asp:RequiredFieldValidator ID="rfvContact" runat="server"
            ErrorMessage="Please enter contact number" ControlToValidate="txtContact"
            Display="Dynamic" ForeColor="Red" SetFocusOnError="True"></asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
    <td>Comments: *</td><td>
        <asp:TextBox ID="txtComments" Width="400" Height="200" runat="server"></asp:TextBox>
        <asp:HtmlEditorExtender ID="HtmlEditorExtender1" TargetControlID="txtComments" EnableSanitization="false" runat="server">
       </asp:HtmlEditorExtender><br />
        <asp:RequiredFieldValidator ID="rfvComments" runat="server"
            ErrorMessage="Please enter your comments" ControlToValidate="txtComments"
            Display="Dynamic" ForeColor="Red" SetFocusOnError="True"></asp:RequiredFieldValidator>
    </td>
    </tr>
    <tr>
    <td></td><td>
        <asp:Button ID="btnSubmit" runat="server" Text="Submit"
            onclick="btnSubmit_Click" />
        <asp:Label ID="lblStatus" runat="server" Text=""></asp:Label>
        </td>
    </tr>
    </table>
    </fieldset>
    </div>
Note : Have you noticed on the design page(ContactUs.aspx) a new directive:
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
is automatically added on dragging the HtmlEditorExtender control form Ajax toolkit in the very second line just below the <@page> directive which is always very first line of the design page(.aspx). This means Ajax is now registered to be used. If this line is not added then add it manually.

Asp.Net C# Code to create contact us form and use Ajax HtmlEditorExtender control 
  • In the Code behind file(ContacUs.aspx.cs) write the code as:
using System.Configuration;
using System.Net;
using System.Net.Mail;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            lblStatus.Text = string.Empty;
        }
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (sendMail())
        {
            lblStatus.Text = "Request Email has been sent successfully";
            ClearControls();
        }
        else
        {
            lblStatus.Text = "Email has not been sent";
            return;
        }
    }

    private bool sendMail()
    {
        SmtpClient smtp = new SmtpClient();
        try
        {
            smtp.Credentials = new NetworkCredential("YourGmailEmailId@gmail.com", "YourGmailPassword");
            smtp.Port = 587;
            smtp.Host = "smtp.gmail.com";
            smtp.EnableSsl = true;

            MailMessage message = new MailMessage();
            message.From = new MailAddress("YourGmailEmailId@gmail.com");
            message.To.Add(txtEmail.Text.Trim());
            message.Subject = "Write your subject here";
            message.Body = "<b>Contact Request From :</b>  <br/><br>Name: " +  txtName.Text.Trim() + "<br/><br> Email Address: " + txtEmail.Text.Trim() + "<br/><br> ContactNo: " + txtContact.Text.Trim() + "<br/><br>Comments: " + txtComments.Text + "<br>";
            message.IsBodyHtml = true;
            smtp.Send(message);
            return true;
        }
        catch (Exception ex)
        {
            lblStatus.Text = "Exxor Occured:" + ex.Message.ToString();
            return false;
        }
    }

    private void ClearControls()
    {
        txtName.Text = string.Empty;
        txtEmail.Text = string.Empty;
        txtContact.Text = string.Empty;
        txtComments.Text = string.Empty;
    }


Asp.Net VB Code to create contact us form and use Ajax HtmlEditorExtender control
  • In the Code behind file(ContactUs.aspx.vb) write the following code:
Imports System.Configuration
Imports System.Net
Imports System.Net.Mail

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            lblStatus.Text = String.Empty
        End If
    End Sub

    Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click
        If sendMail() Then
            lblStatus.Text = "Request Email has been sent successfully"
            ClearControls()
        Else
            lblStatus.Text = "Email has not been sent"
            Return
        End If
    End Sub

    Private Function sendMail() As Boolean
        Dim smtp As New SmtpClient()
        Try
            smtp.Credentials = New NetworkCredential("YourGmailEmailId@gmail.com", "YourGmailpassword")
            smtp.Port = 587
            smtp.Host = "smtp.gmail.com"
            smtp.EnableSsl = True

            Dim message As New MailMessage()
            message.From = New MailAddress("YourGmailEmailId@gmail.com")
            message.[To].Add(txtEmail.Text.Trim())
            message.Subject = "Write your subject here"
            message.Body = ("<b>Contact Request From :</b>  <br/><br>Name: " & txtName.Text.Trim() & "<br/><br> Email Address: " & txtEmail.Text.Trim() & "<br/><br> ContactNo: " & txtContact.Text.Trim() & "<br/><br>Comments: ") + txtComments.Text & "<br>"
            message.IsBodyHtml = True
            smtp.Send(message)
            Return True
        Catch ex As Exception
            lblStatus.Text = "Error Occured:" & ex.Message.ToString()
            Return False
        End Try
    End Function

    Private Sub ClearControls()
        txtName.Text = String.Empty
        txtEmail.Text = String.Empty
        txtContact.Text = String.Empty
        txtComments.Text = String.Empty
    End Sub

Now over to you:
"If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates."
Previous
Next Post »

16 comments

Click here for comments
Rajesh
admin
August 26, 2013 ×

Very nice...Thanks alot :)

Reply
avatar
Priti Kumari
admin
September 11, 2013 ×

Nice..............

Reply
avatar
September 11, 2013 ×

thanks for appreciating my work..stay tuned and stay connected for more useful updates..

Reply
avatar
September 16, 2013 ×

Thanks for the appreciation arvind..stay connected for more technical updates like this..

Reply
avatar
September 17, 2013 ×

thank you but i get this error when i submit it

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive).

Reply
avatar
September 18, 2013 ×

hello Daban Abdulla, read the article to remove that error easily..
http://www.webcodeexpert.com/2013/06/how-to-solve-webforms.html

Reply
avatar
October 30, 2013 ×

Sir, I want to copy the text from word file and directly want to display those contents in asp.net panel or div with same css.what should i do sir??

Reply
avatar
LUFTAI II
admin
December 07, 2013 ×

Good lesson Sir :)

Reply
avatar
December 08, 2013 ×

Thanks LUFTAI..i am glad you liked my article..keep reading for more useful updates..:)

Reply
avatar
swathy mohan
admin
February 18, 2014 ×

hi sir.... its not displaying the formatting tab..what changes need to be done in web.config file

Reply
avatar
February 19, 2014 ×

Hello swathy mohan..no changes need to be done in web.config..it works as it is..i suggest you to try once again..if still you face problem then let me know..i will help you to sort out your problem..

Reply
avatar
Muhammad Ali
admin
February 20, 2014 ×

thanks alot ,
Good lesson
but what about yahoo mail and hot mail it`s not working with me??

Reply
avatar
April 30, 2014 ×

it's not working with me
let me know reason ??

Reply
avatar
April 30, 2014 ×

Hi, what error you are facing? let me know..i will help you in sorting out that issue..

Reply
avatar

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily.. ConversionConversion EmoticonEmoticon