Thursday, 23 March 2017

Ajax Mvc Captcha Validation With Reload Captcha Button Using Jquery

3/23/2017 - By Pranav Singh 7

This article will show you how you can show captcha code in asp.net mvc with Ajax reload or refresh button for captcha using c#.net. This will be with ajax captcha verification using jquery.

So for this article first we will create a new mvc application and add controller file and add the below code.

        public ActionResult CaptchaImage()
        {
            string[] strArray = new string[36];
            strArray = new string[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };

            Random autoRand = new Random();
            string strCaptcha = string.Empty;
            for (int i = 0; i < 6; i++)
            {
                int j = Convert.ToInt32(autoRand.Next(0, 62));
                strCaptcha += strArray[j].ToString();
            }
            Session["Captcha"] = strCaptcha;
            ImageConverter converter = new ImageConverter();
           // Response.BinaryWrite((byte[])converter.ConvertTo(CaptchaGeneration(strCaptcha), typeof(byte[])));
            Response.Write(Convert.ToBase64String((byte[])converter.ConvertTo(CaptchaGeneration(strCaptcha), typeof(byte[]))));
            return View();
        }
        public Bitmap CaptchaGeneration(string captchatxt)
        {
            Bitmap bmp = new Bitmap(133, 48);
            using (Graphics graphics = Graphics.FromImage(bmp))
            {
                Font font = new Font("Tahoma", 14);
                graphics.FillRectangle(new SolidBrush(Color.Gray), 0, 0, bmp.Width, bmp.Height);
                graphics.DrawString(captchatxt, font, new SolidBrush(Color.Gold), 25, 10);
                graphics.Flush();
                font.Dispose();
                graphics.Dispose();
            }
            return bmp;
        }

 In above code i have added two function first for creating captcha image. Now we will take a ActionResult.

public ActionResult CaptchaOnlyScreen()
        {
            return View();
        }

 Now we will create view and add the below code.

<table>
    <tr>
        <td style="text-align:center;" colspan="2">
            <div id="divCaptcha">@Html.Action("CaptchaImage", "Captcha")</div>
              
            <a href="#" onclick="javascript:ReloadCaptchaCode();"> <img src="~/images/reload.png" border="0" /><b>Reload Captcha</b></a>
        </td>
    </tr>
    <tr>
        <td colspan="2" class="up-profile input">
            <input type="text" name="Code" id="txtCaptcha" style="width:100%;" required oninvalid="this.setCustomValidity('Please enter captcha code.')" oninput="this.setCustomValidity('')" />
        </td>
    </tr>
    <tr>
        <td>
           <input type="button" value="Submit" onclick="javascript:VerifyCaptchaCode()"/>
        </td>
    </tr>
</table>


Now we Will write code to validate the added captcha.

     public string ValidateCaptcha(string Code)
        {
            try
            {
                if (Session["Captcha"].ToString() == Code)
                {
                    return "1";
                }
                else
                {
                    return "0";
                }
            }
            catch { return "0"; }
        }

Now we will write some javascript code to reload the captcha.

//-------------For re-genrating captcha code-----------------
function ReloadCaptchaCode() {
    var url = "/Captcha/CaptchaImage/";
    $('#divCaptcha').html("Loading Captcha....");
    $.ajax({
        url: url,
        cache: false,
        success: function (data) {
            var imag = "
            + "src='" + "data:image/jpg;base64,"
            + data + "'/>";
            $('#divCaptcha').html(imag);
        },
        error: function (reponse) {
            alert("Error while generating captcha. Pleae refresh page and try again.");
        }

    });
}


 Now check the code for validating code.

function VerifyCaptchaCode() {
    var captchacode = $("#txtCaptcha").val();
    if (captchacode != "") {
        var url = "/Captcha/ValidateCaptcha?Code=" + captchacode;
        $('#divVerify').html("Please wait....");
        $.ajax({
            url: url,
            cache: false,
            success: function (data) {
                if (data == "0") {
                    alert("Please enter a valid captcha");
                } else {
alert("Thanks you for adding correct captcha. enter a valid captcha");                }
            },
            error: function (reponse) {
                alert("Error while sending detail. Pleae refresh page and try again.");
            }

        });
    } else {
        alert("Please enter captcha code.");
    }
}

Now we have done.  Now check the output.





About the Author

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Get Updates

Subscribe to our e-mail newsletter to receive updates.

Share This Post

7 comments:

  1. could not find @Html.Action("CaptchaImage", "Captcha") controller n method in above code

    ReplyDelete
    Replies
    1. Hi I have make come changes in code. For html.action u must follow the syntax.
      @Html.Action("","Controller name")
      Here action name will be the ActionResult function name which is returning the captcha image as bmp.
      Please let me kmow if you have any other doubt.
      Thanks

      Delete
  2. The view 'CaptchaImage' or its master was not found or no view engine supports the searched locations

    ReplyDelete
    Replies
    1. Prepare the view same as the name in your controller and replace the path var url = "/Captcha/CaptchaImage/";

      Delete
    2. captcha is not loading only text is showing

      Delete
    3. Its not working at all return base64

      Delete
    4. What the error u r facing. please share the javascript error.

      Delete

Please let me know your view

Free Ebooks


About Us

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Contact Us

For writing article in this website please send request by your

GMAIL ID: dotnetpools@gmail.com

Bugs and Suggestions

As we all know that this website is for sharing knowledge and providing proper solution. So while reading the article is you find any bug or if you have any suggestion please mail us at contact@aspdotnet-pools.com.

Partners


Global Classified : Connectseekers.com
© 2014 aspdotnet-pools.com Designed by Bloggertheme9.
back to top