Captcha

  • 3 min 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.

View code ("Index.cshtml"):

@using (Html.BeginForm()){
    <div>
        @Html.DisplayFor(model => model.Email)
    </div>
    <div>
        @Html.EditorFor(model => model.Email)
    </div>

    <div>
        @Html.DisplayFor(model => model.Password)
    </div>
    <div>
        @Html.EditorFor(model => model.Password)
    </div>
    <div>
        @Html.Partial("_CaptchaPartial")
    </div>
    <div>
    @Html.DevExpress().Button(settings => {
            settings.Name = "Submit";
            settings.Text = "Submit";
        }).GetHtml()
    <div>
}

Partial View code ("_CaptchaPartial.cshtml"):

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

Controller code ("HomeController"):

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