Monday, 27 January 2014

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

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/pageand send the inquiry details by email in asp.net using C# and VB.Net.  Also I have used theHtmlEditorExtender 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. 

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.

C#.Net 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;
    }


VB.Net 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.EventArgsHandles 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.EventArgsHandlesbtnSubmit.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

1 comment:

  1. These are some great tools that i definitely use for SEO work. This is a great list to use in the future..
    加拿大cs代写

    ReplyDelete