Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Captcha Code Implementation in MVC

3.03/5 (11 votes)
3 Jun 2014CPOL 49.6K   3.9K  
Captcha code

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.

Here is step by step code and description.

My model looks like:

C#
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:

C#
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:

C#
@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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)