CAPTCHA on MVC

Written 10/23/2017

The Nuget Package

Open the ASP.NET MVC project, on which you want to implement a mail form with CAPTCHA validation. In case you do not have a project created yet, please create an empty ASP.NET MVC application.
Install a nugget package named CaptchaMvc.Mvc5 to your project. (I assume you use MVC5)

The Model

Create a model called ContactPage.cs

public class ContactPage
{
public string Name { get; set; }
public string Email { get; set; }
public string Message { get; set; }
}

The Controller

Add a controller, named ContactPageController.cs 

public class ContactPageController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(ContactPage contactPage)
if (ModelState.IsValid)
if (!this.IsCaptchaValid("Captcha is not valid")) {
ViewBag.ErrMessage = "Error: captcha is not valid.";
return View();
}
try
{
// logic for sending the message
return View("Success");
}
catch (Exception ex)
{
return View("Error");
}
}
return View();
}
}


The views

Create two views in a folder named ContactPage under the Views folder:
Index.cshtml:

@using CaptchaMvc.HtmlHelpers
@model NameOfYourProject.Models.ContactPage
<h2>Contact Me</h2>
@using (Html.BeginForm()
{
@Html.ValidationSummary(true)
<div class="row">
@Html.LabelFor(model => model.Name, "Name:")
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => FirstName)
</div>
<div class="row">
@Html.LabelFor(model => model.Email, "Email:")
@Html.EditorFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)
</div>
<div class="row">
@Html.LabelFor(model => model.Message, "Message:")
@Html.TextAreaFor(model => model.Message)
@Html.ValidationMessageFor(model => model.Message)
</div>
<div class="row">
@Html.MathCaptcha()
@*@Html.Captcha(3)*@
<br />
<p class="Error"> @ViewBag.ErrMessage </p>
</div>
<div class="row">
<input type="submit" value="submit" />
<input type="reset" value="reset" />
</div>
}

and Success.cshtml

@{ 
ViewBag.Title = "Success";
}
<h2>Success</h2>
<p>Your message was sent successfully. I will get back to you as soon as possible.</p>