ASP.NET MVC 5.0 jQuery Ajax CAPTCHA VB.NET Code Sample (BotDetect v3.0; deprecated)

The ASP.NET MVC 5.0 jQuery Ajax Captcha VB.NET sample project shows how to perform Ajax Captcha validation using a jQuery $.getJSON call on the client combined with an ASP.NET MVC 5.0 JsonResult Controller action on the server.

First Time Here?

Check the BotDetect ASP.NET MVC Captcha Quickstart for key integration steps.

Both the client-side code (located in Scripts\CheckCaptcha.js) and the server-side code (Controllers\SampleController.vb) are very simple, and allow BotDetect Captcha protection to be added in a variety of custom Ajax forms and scenarios.

→ ASP.NET MVC version:

→ .NET programming language:

  • C#
  • VB.NET

Installed Location

By default, the .NET 4.5 VB.NET Razor version of the ASP.NET MVC 5.0 jQuery Ajax Captcha sample project is installed at:
C:\Program Files\Lanapsoft\BotDetect 3 CAPTCHA Component\Asp.Net\v4.5\WebApp\AspNetMvc50AjaxCaptchaSample\VBNet

You can also run it from the BotDetect Start Menu:
Programs > Lanapsoft > BotDetect 3 CAPTCHA Component > ASP.NET > DotNET 4.5 Web Applications > Run


@* namespaces needed to access BotDetect members and the CaptchaHelper class 
@Imports BotDetect.Web.UI.Mvc

    Layout = Nothing
End Code

<!DOCTYPE html>

<head runat="server">
    <meta name="viewport" content="width=device-width" />
    <title>BotDetect ASP.NET MVC 5.0 jQuery Ajax CAPTCHA Sample VB.NET</title>
    <link href="@Url.Content("~/Style/Sheet.css")" rel="stylesheet" type="text/css" />
    <link href="@BotDetect.Web.CaptchaUrls.Absolute.LayoutStyleSheetUrl" 
      rel="stylesheet" type="text/css" />
    <h1>BotDetect ASP.NET MVC 5.0 jQuery Ajax CAPTCHA Sample</h1>
    @Using Html.BeginForm()
            <legend>CAPTCHA Validation Using jQuery Ajax</legend>
                @Html.Label("CaptchaCode", "Retype the code from the picture:")
                @Code Dim sampleCaptcha As MvcCaptcha = New MvcCaptcha("SampleCaptcha")
                sampleCaptcha.UserInputClientID = "CaptchaCode"End Code
            <div class="actions">
                <span class="status" id="status">Not checked yet</span>
                <a href="#" id="check">Check</a>
        @<script src="@Url.Content("~/Scripts/jquery-2.1.0.js")"></script>
        @<script src="@Url.Content("~/Scripts/CheckCaptcha.js")"></script>
    End Using

To display Captcha protection on the sample View, we first ensure we can use BotDetect members and the application code by Import-ing the relevant namespace. We then create a MvcCaptcha instance, and add it to the form by calling the Html.Captcha() Html helper with it.

The jQuery Ajax Captcha validation code is kept in a JavaScript file called CheckCaptcha.js, which we include at the bottom of the form.

Since we want to show a general case of getting the Captcha validation result with an Ajax call, the form is not submitted with a button, but we add a link which will start Ajax Captcha validation when clicked (as will be shown in client-side code).


Imports BotDetect.Web
Imports BotDetect.Web.UI.Mvc

Namespace AspNetMvc50AjaxCaptchaSampleVBNet
    Public Class SampleController
        Inherits System.Web.Mvc.Controller

        ' /Sample/Index
        Function Index() As ActionResult
            Return View()
        End Function

        ' GET: /Sample/CheckCaptcha
        <OutputCache(Location:=OutputCacheLocation.None, NoStore:=True)> _
        Function CheckCaptcha(ByVal captchaId As String, ByVal instanceId As 
          String, ByVal userInput As String) As JsonResult
            Dim ajaxValidationResult As Boolean = CaptchaControl.AjaxValidate(
              captchaId, userInput, instanceId)
            Return Json(ajaxValidationResult, JsonRequestBehavior.AllowGet)
        End Function

    End Class
End Namespace

To get the Captcha validation result, we call the static Validate() method from the CaptchaControl API. The parameters it takes are:

  1. captchaId is the identifier of the Captcha instance we passed to the MvcCaptcha constructor in CaptchaHelper code.
  2. userInput is the sequence of characters the user retyped from the Captcha image before starting validation.
  3. instanceId is the unique identifier of the Captcha code we are validating, which the calling script reads from the client-side Captcha object.

The validation call is executed within an action returning a JsonResult, for which we also disabled all caching using the OutputCache attribute. Caching the result makes no sense since each Captcha code can only be validated once.

It's important to note that this sample only shows how to perform Ajax Captcha validation in an ASP.NET MVC application using jQuery. Depending on how you intend to use Captcha protection, you should also ensure that bots you're trying to block (which mostly don't execute client-side code at all) can't trivially bypass your client-side security measures, as explained in the BotDetect FAQ.


$(document).ready(function () {
    $('#check').click(function checkForm(event) {

        $('#status').attr('class', 'inProgress');

        // get client-side Captcha object instance
        var captchaObj = $("#CaptchaCode").get(0).Captcha;

        // gather data required for Captcha validation
        var params = {}
        params.CaptchaId = captchaObj.Id;
        params.InstanceId = captchaObj.InstanceId;
        params.UserInput = $("#CaptchaCode").val();

        // make asynchronous Captcha validation request
        $.getJSON('Sample/CheckCaptcha', params, function (result) {
            if (true === result) {
                $('#status').attr('class', 'correct');
                $('#status').text('Check passed');
            } else {
                $('#status').attr('class', 'incorrect');
                $('#status').text('Check failed');
                // always change Captcha code if validation fails


The Ajax Captcha validation request is made using the $.getJSON() jQuery function, and goes to the Url of the MVC Controller + Action performing Captcha validation in server-side code.

To get the captchaId and instanceId parameters we need for the Captcha validation call, we first get the client-side Captcha object which was automatically added to the Captcha code textbox.

Since we want to keep this sample simple and generic enough to be useful for diverse Ajax Captcha use-cases, we just display the validation result directly on the form. What we need to do in any use-case is reload the Captcha image if validation failed, since each random Captcha code can only be attempted once for security reasons, and the user must be shown a new code.


Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.Mvc
Imports System.Web.Routing

Public Class RouteConfig
    Public Shared Sub RegisterRoutes(ByVal routes As RouteCollection)

        ' BotDetect requests must not be routed
          New With {.botdetect = "(.*)BotDetectCaptcha\.ashx"})

        routes.MapRoute( _
            name:="Default", _
            url:="{controller}/{action}/{id}", _
            defaults:=New With {.controller = "Sample", .action = "Index", 
              .id = UrlParameter.Optional} _
    End Sub
End Class

We configure ASP.NET Routing to ignore BotDetect requests, since they do not conform to any MVC-related patterns. The regex defining requests to ignore must match the path configured for the BotDetect HttpHandler registered in web.config.


<?xml version="1.0" encoding="utf-8"?>
  For more information on how to configure your ASP.NET application, please visit
    <section name="botDetect" requirePermission="false" 
      type="BotDetect.Configuration.BotDetectConfigurationSection, BotDetect"/>
    <add key="webpages:Version" value=""/>
    <add key="webpages:Enabled" value="false"/>
    <add key="ClientValidationEnabled" value="false"/>
    <add key="UnobtrusiveJavaScriptEnabled" value="false"/>
    <compilation debug="false" targetFramework="4.5.1"/>
    <httpRuntime targetFramework="4.5.1"/>
    <!-- configure Session State for BotDetect use -->
    <sessionState mode="InProc" cookieless="AutoDetect" timeout="20" 
      sessionIDManagerType="BotDetect.Web.CustomSessionIdManager, BotDetect"/>
      <!-- register HttpHandler used for BotDetect Captcha requests -->
      <add verb="GET" path="BotDetectCaptcha.ashx" 
        type="BotDetect.Web.CaptchaHandler, BotDetect"/>
    <validation validateIntegratedModeConfiguration="false" />
      <!-- register HttpHandler used for BotDetect Captcha requests -->
      <remove name="BotDetectCaptchaHandler"/>
      <add name="BotDetectCaptchaHandler" preCondition="integratedMode" verb="GET" 
        path="BotDetectCaptcha.ashx" type="BotDetect.Web.CaptchaHandler, BotDetect"/>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="" newVersion=""/>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="" newVersion=""/>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="" newVersion=""/>
      <helpLink enabled="true" mode="image"/>

To allow the application to use BotDetect Captcha protection, we must register the BotDetect HttpHandler in both <system.web><httpHandlers> and <system.webServer><handlers> configuration sections, and enable and configure ASP.NET sessionState.

The <dependentAssembly> entry for System.Web.Mvc is also needed to make all ASP.NET MVC dependencies referenced by the BotDetect MVC assembly point to the correct ASP.NET MVC version.

Please Note

The information on this page is out of date and applies to a deprecated version of BotDetect™ CAPTCHA (v3.0).

An up-to-date equivalent page for the latest BotDetect Captcha release (v4) is BotDetect v4 Captcha documentation index.

General information about the major improvements in the current BotDetect release can be found at the What's New in BotDetect v4.0 page.