Thursday, November 22, 2012

Make a Captcha Image Validation with Jquery and MVC

 http://www.codeproject.com/Tips/494536/Make-a-Captcha-Image-Validation-with-Jquery-and-MV

   <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> 


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);
        }