Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Make a Captcha Image Validation with Jquery and MVC

0.00/5 (No votes)
16 Nov 2012 1  
This code generates an image for captcha validation

Introduction

The code snippets below show how to use a simple class to create a validation mechanism via captcha in ASP.NET, using Jquery and MVC.

Using the Code

The code consists of two parts that work together to make the code work.

The first is JavaScript that runs on the client and should be placed on the page header. It is responsible for making the request to the server.

Note: I must remember that this JavaScript code requires Jquery, which can be downloaded here.

   <script type="text/javascript" language="javascript">
        $(document).ready(function () {
            loadCaptcha();
        });
        function loadCaptcha() {
            $.ajax({
                type: 'GET', url: 'Home/generateCaptcha',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                cache: false,
                success: function (data) { $("#m_imgCaptcha").attr('src', data); },
                error: function (data) { alert("Error while loading captcha image") }
            });
        }
    </script> 

The second is C# runs on the server. That receives the request from the page, generates an image with the specified text. This text can be generated by a function embedded in class or can be specified by the developer. The text is saved in the Session and is used to validate the data entered by the user.

 public ActionResult generateCaptcha()
        {
            System.Drawing.FontFamily family = new System.Drawing.FontFamily("Arial");
            CaptchaImage img = new CaptchaImage(150, 50, family);
            string text = img.CreateRandomText(4) + " " + img.CreateRandomText(3);
            img.SetText(text);
            img.GenerateImage();
            img.Image.Save(Server.MapPath("~") + 
            this.Session.SessionID.ToString() + ".png", 
            System.Drawing.Imaging.ImageFormat.Png);
            Session["captchaText"] = text;
            return Json(this.Session.SessionID.ToString() + ".png?t=" + 
            DateTime.Now.Ticks, JsonRequestBehavior.AllowGet);
        } 

Here is an example of a captcha image generated using this code:

Advantages of Use

  • You know what's running on your server.
  • No special settings are needed.
  • It is not necessary use third party components that can fail.
  • It is fully customizable.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here