Menu

Contact Us form in MVC 3.0 with Captcha

Hello Friend,

Here I have gave demo for Contact Us form in MVC with Captcha.

Download Source Code :=>ContactUsFormInMVC3.rar

Result.

contactus1

Check All Validation

contactus2

Captcha Validation

contactus3

Email Successfully send

contactus4

Now start coding.

Step 1. Create model

ContactUs.cs


using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using System.ComponentModel.DataAnnotations;

namespace ContactUsFormInMVC3.Models

{

public class Captcha

{

[AllowHtml]

[Display(Name = "Captcha", Order = 20)]

[Required(ErrorMessage = "Please enter captcha.")]

[RegularExpression(@"^([^<]|<p>|</p>|<strong>|</strong>|a z|A Z|1 9|(.\.))*$", ErrorMessage = "Please do not enter html tags as captcha.")]

public virtual string CaptchaValue { get; set; }

public Captcha()

{

CaptchaValue = string.Empty;

}

}

public class InvisibleCaptcha

{

[AllowHtml]

[Display(Name = "InvisibleCaptcha", Order = 20)]

[Remote("ValidateInvisibleCaptcha", "Captcha", "", ErrorMessage = "ErrorMessage")]

public virtual string InvisibleCaptchaValue { get; set; }

public InvisibleCaptcha() { }

}

}

Captcha.cs


using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using System.ComponentModel.DataAnnotations;

namespace ContactUsFormInMVC3.Models

{

public class Captcha

{

[AllowHtml]

[Display(Name = "Captcha", Order = 20)]

[Required(ErrorMessage = "Please enter captcha.")]

[RegularExpression(@"^([^<]|<p>|</p>|<strong>|</strong>|a z|A Z|1 9|(.\.))*$", ErrorMessage = "Please do not enter html tags as captcha.")]

public virtual string CaptchaValue { get; set; }

public Captcha()

{

CaptchaValue = string.Empty;

}

}

public class InvisibleCaptcha

{

[AllowHtml]

[Display(Name = "InvisibleCaptcha", Order = 20)]

[Remote("ValidateInvisibleCaptcha", "Captcha", "", ErrorMessage = "ErrorMessage")]

public virtual string InvisibleCaptchaValue { get; set; }

public InvisibleCaptcha() { }

}

}

 Step 2. Create Controller

CaptchaController.cs


using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using System.Text;

using System.Drawing;

using System.Security.Cryptography;

using System.Drawing.Drawing2D;

using System.IO;

using System.Drawing.Imaging;

namespace ContactUsFormInMVC3.Controllers

{

/// <summary>

/// This class is fully self-contained. All Captcha related code including

/// handling of session veriables, hashing, validation etc. is located here.

/// In order to use this class include the following image tag somwhere in

/// your view, e.g. in the view handling the registration process:

/// <img src='/Captcha/Show' alt="" />

/// </summary>

public class CaptchaController : Controller

{

public JsonResult ValidateCaptcha(string CaptchaValue)

{

bool b = IsValidCaptchaValue(CaptchaValue.ToUpper());

if (!b) return Json(string.Empty, JsonRequestBehavior.AllowGet);

else return Json(true, JsonRequestBehavior.AllowGet);

}

public JsonResult ValidateInvisibleCaptcha(string CaptchaValue)

{

bool b = CaptchaValue == "";

if (!b) return Json(string.Empty, JsonRequestBehavior.AllowGet);

else return Json(true, JsonRequestBehavior.AllowGet);

}

private const int height = 30;

private const int width = 80;

private const int length = 4;

private const string chars = "ABCDEFGHIJKLMNPQRSTUVWXYZ123456789";

public ActionResult Show()

{

var randomText = GenerateRandomText(length);

var hash = ComputeMd5Hash(randomText + GetSalt());

Session["CaptchaHash"] = hash;

var rnd = new Random();

var fonts = new[] { "Verdana", "Times New Roman" };

float orientationAngle = rnd.Next(0, 359);

var index0 = rnd.Next(0, fonts.Length);

var familyName = fonts[index0];

using (var bmpOut = new Bitmap(width, height))

{

var g = Graphics.FromImage(bmpOut);

var gradientBrush = new LinearGradientBrush(new Rectangle(0, 0, width, height),

Color.White, Color.DarkGray,

orientationAngle);

g.FillRectangle(gradientBrush, 0, 0, width, height);

DrawRandomLines(ref g, width, height);

g.DrawString(randomText, new Font(familyName, 18), new SolidBrush(Color.Green), 0, 2);

var ms = new MemoryStream();

bmpOut.Save(ms, ImageFormat.Png);

var bmpBytes = ms.GetBuffer();

bmpOut.Dispose();

ms.Close();

return new FileContentResult(bmpBytes, "image/png");

}

}

public static bool IsValidCaptchaValue(string captchaValue)

{

var expectedHash = System.Web.HttpContext.Current.Session["CaptchaHash"];

var toCheck = captchaValue + GetSalt();

var hash = ComputeMd5Hash(toCheck);

return hash.Equals(expectedHash);

}

private static void DrawRandomLines(ref Graphics g, int width, int height)

{

var rnd = new Random();

var pen = new Pen(Color.Gray);

for (var i = 0; i < 10; i++)

{

g.DrawLine(pen, rnd.Next(0, width), rnd.Next(0, height),

rnd.Next(0, width), rnd.Next(0, height));

}

}

private static string GetSalt()

{

return typeof(CaptchaController).Assembly.FullName;

}

private static string ComputeMd5Hash(string input)

{

var encoding = new ASCIIEncoding();

var bytes = encoding.GetBytes(input);

HashAlgorithm md5Hasher = MD5.Create();

return BitConverter.ToString(md5Hasher.ComputeHash(bytes));

}

private static string GenerateRandomText(int textLength)

{

var random = new Random();

var result = new string(Enumerable.Repeat(chars, textLength)

.Select(s => s[random.Next(s.Length)]).ToArray());

return result;

}

}

}

ContactUsController.cs


using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using ContactUsFormInMVC3.Models;

using System.Data;

using System.Text;

using System.Net.Mail;

using System.Net.Mime;

namespace ContactUsFormInMVC3.Controllers

{

public class ContactUsController : Controller

{

//

// GET: /ContactUs/

public ActionResult Index(string result)

{

ViewBag.Sent = result;

ContactUs objContactUs = new ContactUs();

if (TempData["ContactUs"] != null)

{

ViewBag.IsInvalid = 1;

ModelState.AddModelError(string.Empty, "Please enter valid captcha Code.");

objContactUs = (ContactUs)TempData["ContactUs"];

Session["ContactUs"] = null;

}

else

{

ViewBag.IsInvalid = 0;

}

return View(objContactUs);

}

//Send Mail

[HttpPost]

public ActionResult Index(ContactUs objContactUs, string CaptchaValue, string InvisibleCaptchaValue)

{

bool cv = CaptchaController.IsValidCaptchaValue(CaptchaValue);

bool icv = InvisibleCaptchaValue == "";

if (!cv || !icv)

{

TempData["ContactUs"] = objContactUs;

return RedirectToAction("Index");

}

try

{

if (ModelState.IsValid)

{

TempData["ContactUs"] = null;

string isSent = SendContactus(objContactUs.Name, objContactUs.Email, objContactUs.WebSite, objContactUs.Subject, objContactUs.Description);

if (string.IsNullOrEmpty(isSent) == true)

{

return RedirectToAction("Index", new { result = "1" });

}

else

{

return RedirectToAction("Index", new { result = "0" });

}

}

}

catch (DataException)

{

ModelState.AddModelError("", "Unable to save. Try again, and if the problem persists, contact system administrator.");

}

return View(objContactUs);

}

private static string GetContactUsBody(string name, string emailId, string website, string subject, string description)

{

StringBuilder adminBody = new StringBuilder();

adminBody.Append("<tr> <td style='padding: 20px 8px 8px;'>");

adminBody.Append("<table width='100%' cellspacing='0' cellpadding='2' align='center' border='0' style='border: 1px solid #26ABE3;'>");

adminBody.Append("<tbody>");

adminBody.Append("<tr width='620px'><td align='left' valign='top'>");

adminBody.Append("<b>Name </b>  </td><td>" + name.Trim());

adminBody.Append("</td></tr>");

adminBody.Append("<tr width='620px'><td align='left' valign='top'>");

adminBody.Append("<b> Email </b></td><td align='left'>" + emailId.Trim());

adminBody.Append("</td></tr>");

if (!string.IsNullOrEmpty(website))

{

adminBody.Append("<tr width='620px'><td align='left' valign='top' >");

adminBody.Append("<b>WebSite</b></td><td align='left' >" + website.Trim());

adminBody.Append("</td></tr>");

}

adminBody.Append("<tr width='620px'><td align='left' valign='top'>");

adminBody.Append("<b> Subject </b></td><td align='left'>" + subject.Trim());

adminBody.Append("</td></tr>");

adminBody.Append("<tr width='620px'><td align='left' valign='top' >");

adminBody.Append("<b> Description </b></td><td align='left'> " + description.Trim());

adminBody.Append("</td></tr>");

adminBody.Append("</tbody></table>");

adminBody.Append("</td> </tr>");

return adminBody.ToString();

}

public static string SendContactus(string name, string emailId, string website, string subject, string description)

{

string body = GetContactUsBody(name, emailId, website, subject, description);

return SendEMailMessage("Contact Us", body, "Contact us");

}

public static string SendEMailMessage(string EMailName, string EmailBody, string EmailSubject)

{

#region Set parameter

string SmtpServer = "smtpServer";

string SmtpUser = "UserName";

string SmtpPassword = "Password";

string SmtpEmailFrom = "Email From";

string EmailTo = "Email To";

#endregion

int intYear = DateTime.Now.Year;

string errorMsg = "";

SmtpClient SmtpMail = new SmtpClient();

MailMessage message = new MailMessage();

int getYear = DateTime.Now.Year;

string strHeader = "<html><table width='627px' cellspacing='0' cellpadding='0' align='center' border='0' style='background: none repeat scroll 0% 0% #FFFFFF; border: 1px solid #26ABE3;'> <tbody> <tr><td style='padding: 10px;'><img width='169' height='102' src='cid:companylogo' /></td></tr>";

string strFooter = "<tr><td style='background-color:#FFFFFF;padding: 10px;'><div align='center'><span style='font-family: Arial,Helvetica,sans-serif; font-size: 10px; color: #707070;'>Copyright &amp;amp;amp;amp;amp;amp;amp;amp;copy; " + intYear + " JG Consultant Engineerings. All Rights Reserved.</span></div></td></tr></tbody></table></html>";

AlternateView av1 = AlternateView.CreateAlternateViewFromString(strHeader + EmailBody + strFooter, null, MediaTypeNames.Text.Html);

message.AlternateViews.Add(av1);

message.IsBodyHtml = true;

try

{

SmtpMail.Host = SmtpServer;

SmtpMail.UseDefaultCredentials = false;

SmtpMail.Credentials = new System.Net.NetworkCredential(SmtpUser, SmtpPassword);//Check the credentials

MailAddress fromAddress = new MailAddress(SmtpEmailFrom, EMailName);// Set the sender address of the mail message

message.From = fromAddress;

message.Sender = fromAddress; // Set the recepient address of the mail message

message.To.Add(EmailTo); // Set the subject of the mail message

message.Subject = EmailSubject; // Set the format of the mail message body as HTML

message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

SmtpMail.Send(message);

}

catch (Exception ex)

{

errorMsg = ex.Message;

}

return errorMsg;

}

}

}

Note Please set your SMTP detail in above code.

string SmtpServer = “smtpServer”;

string SmtpUser = “UserName”;

string SmtpPassword = “Password”;

string SmtpEmailFrom = “Email From”;

string EmailTo = “Email To”;

 

Step 3. Create view

_Captcha.cshtml


@model ContactUsFormInMVC3.Models.Captcha

<div class="company-box">

<div style="float: left; margin-right: 10px;">

<img src='@Url.Content("~/Captcha/Show")' alt="" class="captcha_img" />

</div>

<div class="captcha-mid">

@Html.TextBoxFor(m => m.CaptchaValue, new { @class = "captcha_input" })

</div>

</div>

<div class="errorMsgContent">

@Html.ValidationMessageFor(m => m.CaptchaValue)

</div>

_InvisibleCaptcha.cshtml


@model ContactUsFormInMVC3.Models.InvisibleCaptcha

<div style="display:none;">

<div class="editor-label">

@Html.LabelFor(model => model.InvisibleCaptchaValue)

</div>

<div class="editor-field">

@Html.EditorFor(model => model.InvisibleCaptchaValue)

@Html.ValidationMessageFor(model => model.InvisibleCaptchaValue)

</div>

</div>

Index.cshtml


@model  ContactUsFormInMVC3.Models.ContactUs

@{

ViewBag.Title = "Contact us | *** Developer's Solution ***";

Layout = "/Views/Shared/_Layout.cshtml";

}

@{

if (Convert.ToInt32(@ViewBag.IsInvalid) == 1)

{

<script type="text/javascript">

$(function () {

$("#CaptchaValue").focus();

});

</script>

}

else

{

<script type="text/javascript">

$(function () {

$("#Name").focus();

});

</script>

}

}

<div class="mainLeft">

<h1>

Contact Us

</h1>

<div class="contactUsContent">

<div class="quote-form-back">

<div class="quote-form-area">

@using (Html.BeginForm("Index", "ContactUs", FormMethod.Post, new { enctype = "multipart/form-data" }))

{

<div class="quote-form">

<div class="form-fill-area">

<div class="errorMsg">

@if (@ViewBag.Sent == "1")

{

<div class="notification success">

Thank you for choosing Develope's Solution. We will get back to you as soon as possible!.

</div>

}

else if (@ViewBag.Sent == "0")

{

<div class="notification error">

Email has not sent. Please try again.

</div>

}

</div>

<div class="errorMsg">

<div class="feild-name">

</div>

<div class="errorMsgContent">

@Html.ValidationSummary(true)

</div>

</div>

<div class="form-line1">

<div class="feild-name">

@Html.LabelFor(m => m.Name)<span>*</span>

</div>

<div class="company-box">

<div class="com-mid">

@Html.TextBoxFor(m => m.Name)

</div>

</div>

<div class="errorMsgContent">

@Html.ValidationMessageFor(m => m.Name)

</div>

</div>

<div class="form-line1">

<div class="feild-name">

@Html.LabelFor(m => m.Email)

<span>*</span>

</div>

<div class="company-box">

<div class="com-mid">

@Html.TextBoxFor(m => m.Email)

</div>

</div>

<div class="errorMsgContent">

@Html.ValidationMessageFor(m => m.Email)

</div>

</div>

<div class="form-line1">

<div class="feild-name">

@Html.LabelFor(m => m.WebSite)

</div>

<div class="company-box">

<div class="com-mid">

@Html.TextBoxFor(m => m.WebSite)

</div>

</div>

<div class="errorMsgContent">

@Html.ValidationMessageFor(m => m.WebSite)

</div>

</div>

<div class="form-line1">

<div class="feild-name">

@Html.LabelFor(m => m.Subject)

<span>*</span>

</div>

<div class="company-box">

<div class="com-mid">

@Html.TextBoxFor(m => m.Subject)

</div>

</div>

<div class="errorMsgContent">

@Html.ValidationMessageFor(m => m.Subject)

</div>

</div>

<div class="form-line1">

<div class="feild-name">

@Html.LabelFor(m => m.Description)

<span>*</span>

</div>

<div class="comment-box">

<div class="comment-mid">

@Html.TextAreaFor(m => m.Description)

</div>

</div>

<div class="errorMsgContent">

@Html.ValidationMessageFor(m => m.Description)

</div>

</div>

<div class="form-line1">

<div class="feild-name">

Captcha <span>*</span>

</div>

@Html.Partial("_Captcha", new ContactUsFormInMVC3.Models.Captcha())

@Html.Partial("_InvisibleCaptcha", new ContactUsFormInMVC3.Models.InvisibleCaptcha())

</div>

<div class="submit-but">

<input type="submit" class="button" value="Submit" />

</div>

</div>

</div>

}

</div>

</div>

</div>

</div>

Thanks.

No comments

Leave a Reply


1 + = 8

Categories