Introduction
After lots of R&D and analysis of example of Captcha image generation and validation in MVC, finally I have decided to implement my custom Captcha code generation because all samples require lots of complex coding. But this is a very simple and quick way and requires less coding. This works fine for my requirement, maybe it will be useful for your needs.
![](https://www.codeproject.com/KB/user-controls/781675/View.png)
Here is step by step code and description.
My model looks like:
public class CaptchaModel
{
public string CapImage { get; set; }
[Required(ErrorMessage = "Verification code is required.")]
[System.ComponentModel.DataAnnotations.Compare("CapImageText",
ErrorMessage = "Captcha code Invalid")]
public string CaptchaCodeText { get; set; }
public string CapImageText { get; set; }
}
My controller looks like:
public ActionResult Index()
{
CaptchaModel obj = new CaptchaModel();
obj.CapImage = "data:image/png;base64," +
Convert.ToBase64String(new CaptchaUtilityClass().VerificationTextGenerator());
obj.CapImageText = Convert.ToString(Session["Captcha"]);
return View(obj);
}
[HttpPost]
public ActionResult Index(CaptchaModel objCap)
{
if (ModelState.IsValid)
{
return RedirectToAction("Thanks");
}
objCap.CapImage = "data:image/png;base64," +
Convert.ToBase64String(new CaptchaUtilityClass().VerificationTextGenerator());
return View("~/Views/Captcha/Index.cshtml", objCap);
}
public ActionResult Thanks()
{
return View();
}
Finally, my view looks like:
@model CaptchaImplementation.Models.CaptchaModel
@using (Html.BeginForm("Index", "Captcha", FormMethod.Post, new { Model }))
{
@Html.ValidationSummary(false)
<img src="@Model.CapImage"
<label class="col-sm-5 control-label">Verification Code* :</label>
@Html.TextBoxFor(t => t.CaptchaCodeText, new { @class = "form-control",
tabindex = "12", placeholder = "Verification Code" })
@Html.HiddenFor(t => t.CapImageText)
@*your action link or submit button*@
}
CaptchaUtilityClass.cs has image generation and random text generation code
Download the attachment.