Skip to main content

Captcha

  • 3 minutes to read

The Captcha is a CAPTCHA component used to verify that data is submitted by a human, and not a robot or script.

#Implementation Details

Captcha is realized by the CaptchaExtension class. Its instance can be accessed via the ExtensionsFactory.Captcha helper method, which is used to add a Captcha extension to a view. This method’s parameter provides access to Captcha settings implemented by the CaptchaSettings class, allowing you to fully customize the extension.

Captcha‘s client counterpart is represented by the ASPxClientCaptcha object.

#Declaration

Captcha can be added to a project in the following manner.

@using (Html.BeginForm()){
        @Html.DisplayFor(model => model.Email)
        @Html.EditorFor(model => model.Email)
        @Html.DisplayFor(model => model.Password)
        @Html.EditorFor(model => model.Password)
        @Html.Partial("_CaptchaPartial")
        @Html.DevExpress().Button(settings => {
            settings.Name = "Submit";
            settings.Text = "Submit";
        }).GetHtml()
}
@Html.DevExpress().Captcha(
    settings => {
        settings.Name = "captcha";
        settings.CallbackRouteValues = new { Controller = "Home", Action = "CaptchaPartial" };
        settings.TextBox.Position = DevExpress.Web.Captcha.ControlPosition.Bottom;

        settings.CodeLength = 6;
        settings.CharacterSet = "abcdefghjklmnpqrstuvxyz23456789";
    }).GetHtml()

Note

The Partial View should contain only the extension’s code.

The static CaptchaExtension.GetIsValid method is used in the Controller code to check whether the entered code is valid.

using DevExpress.Web.Mvc;
using MyProject.Models;
using System.Web.Mvc;

namespace MyProject.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Index(Person person)
        {
            if (ModelState.IsValid && CaptchaExtension.GetIsValid("captcha"))
            {
                return RedirectToAction("Ok");
            }

            return View(person);
        }

        // Returned when the form was filled correctly
        public ActionResult Ok()
        {
            return View(); 
        }

        public ActionResult CaptchaPartial()
        {
            return PartialView("_CaptchaPartial");
        }
    }
}

The code result is demonstrated in the image below.

MVC_Captcha_Overview

#Main Features

#GitHub Example

View Example: How to use AJAX callbacks to validate a Captcha code and submit a form