Create Captcha In ASP.NET MVC

In This article, I’m going to explain that how to create Captcha in ASP.NET MVC Project.

Before start, this, let me know that what is Captcha. Captcha is nothing but it’s a security layer to identify the user before sending data to the server. Nowadays there are many tools that are used to send automated messages. If we have not implemented Captcha on our page then we will get many spam messages or users. So mainly Captcha is used to avoid spam messages or users.

Let’s Start It

  1. On the Visual Studio, create a new ASP.NET MVC Web Application project.
  2. Add CaptchaMVC.MVC5  library in your project.

In the Controllers folder, create a new controller if you want to use a specific controller. Here I’m using a Home controller.

using CaptchaMvc.HtmlHelpers;
using System;
using System.Web.Mvc;

namespace Captcha.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult ValidateCaptcha()
        {
            if (!this.IsCaptchaValid(""))
            {
                ViewBag.error = "Invalid Captcha";
                return View("Index");
            }
            else
            {
                return View("Success");
            }
        }
        public ActionResult Success()
        {
            return View();
        }
    }
}

In the above controller, the Index method is for the view which will display Captcha. The ValidateCaptcha method, as its name, suggests, will validate the Captcha. The Success method is for the view after Captcha is valid.

Below is my view code. Do not forget to add @using CaptchaMvc.HtmlHelpers the namespace in your view. @Html.Captcha(5) is used to generate Captcha. Number 5 in @Html.Captcha(5) indicates the length of the Captcha. You can change it as you want.

@using CaptchaMvc.HtmlHelpers;

@{
    ViewBag.Title = "Home Page";
}
@using (Html.BeginForm("ValidateCaptcha", "Home", FormMethod.Post))
{
    <div class="container" id="CaptchaDiv">
        <h3>Captcha Demo</h3>
        <div class="row">
            <div class="col-lg-4 form-group">
                @Html.Captcha(5)
                <br />
                <span style="color:red">@ViewBag.error</span>
            </div>
        </div>
        <div class="row">
            <div class="col-lg-4">
                <input type="submit" class="btn btn-primary" id="btnSubmit" value="Submit" />
            </div>
        </div>
    </div>
}

Success View

I have just written one tag in this view. you can modify it as per your requirement.

@{
    ViewBag.Title = "Success";
}

<h1>Thank You</h1>

Final Output

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories