ASP.NET MVC 4.0 jQuery Ajax CAPTCHA VB.NET ASPX Code Example

The ASP.NET MVC 4.0 jQuery Ajax Captcha VB.NET ASPX example project shows how to perform Ajax Captcha validation using a jQuery $.getJSON call on the client combined with an ASP.NET MVC 4.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\ExampleController.vb) are very simple, and allow BotDetect Captcha protection to be added in a variety of custom Ajax forms and scenarios.

Download the BotDetect ASP.NET CAPTCHA Component and run this example

→ ASP.NET MVC version:

→ .NET programming language:

  • C#
  • VB.NET

→ View engine:

Installed Location

By default, the .NET 4.5 VB.NET ASPX version of the ASP.NET MVC 4.0 jQuery Ajax Captcha example project is installed at:
C:\Program Files\Captcha Inc\BotDetect 4 CAPTCHA Component\Asp.Net\.NET4.5\WebApp\AspNetMvc40AjaxCaptchaExample\ASPX\VBNet

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


<%@ Page Language="VB" Inherits="System.Web.Mvc.ViewPage" %>

<%-- namespaces needed to access BotDetect members and the CaptchaHelper class --
<%@ Import Namespace="BotDetect.Web.Mvc" %>
<%@ Import Namespace="AspNetMvc40AjaxCaptchaExampleAspxVBNet" %>

<!DOCTYPE html>

<head runat="server">
  <meta name="viewport" content="width=device-width" />
  <title>BotDetect ASP.NET MVC 4.0 jQuery Ajax CAPTCHA Example ASPX VB.NET</title>
  <link href="<%: Url.Content("~/Style/Sheet.css") %>" rel="stylesheet" 
  type="text/css" />
  <link href="<%: Url.Content("~/" + BotDetect.Web.CaptchaUrls.LayoutStyleSheetUrl) %>" rel="stylesheet" type="text/css" />
  <h1>BotDetect ASP.NET MVC 4.0 jQuery Ajax CAPTCHA Example</h1>

  <% Using Html.BeginForm()%>
    <legend>CAPTCHA Validation Using jQuery Ajax</legend>
      <%: Html.Label("CaptchaCode", "Retype the code from the picture:") %>
      <% Dim exampleCaptcha As MvcCaptcha = CaptchaHelper.GetExampleCaptcha()%>
      <%: Html.Captcha(exampleCaptcha) %>
    <div class="actions">
      <%: Html.TextBox("CaptchaCode") %>
      <span class="status" id="status">Not checked yet</span>
      <a href="#" id="check">Check</a>

  <script src="<%: Url.Content("~/Scripts/jquery-1.7.1.js") %>"></script>
  <script src="<%: Url.Content("~/Scripts/CheckCaptcha.js") %>"></script>
  <% End Using %>

To display Captcha protection on the example View, we first ensure we can use BotDetect members and the application code by Import-ing the relevant namespaces.

We then use the CaptchaHelper to 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.Mvc
Imports System.Web.Mvc

Namespace AspNetMvc40AjaxCaptchaExampleAspxVBNet
  Public Class ExampleController
    Inherits System.Web.Mvc.Controller

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

    ' GET: /Example/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 = Captcha.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 MvcCaptcha 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 example 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.


Imports BotDetect.Web.Mvc

Public Class CaptchaHelper

  Public Shared Function GetExampleCaptcha() As MvcCaptcha

    ' create the control instance
    Dim exampleCaptcha As MvcCaptcha = New MvcCaptcha("ExampleCaptcha")

    ' set up client-side processing of the Captcha code input textbox
    exampleCaptcha.UserInputID = "CaptchaCode"

    Return exampleCaptcha

  End Function

End Class

Since there are many properties of the Captcha object you might want to set, we separate MvcCaptcha instance creation in a class apart from View code. This way we keep the View code short, and can have multiple Captchas in different Views without having to keep Captcha code scattered over each View code.

Each Captcha instance should have a unique ID, which we pass to the MvcCaptcha constructor (and which is also used in the Captcha validation call in Controller code).

Setting the UserInputID property to the client-side ID of the Captcha code input textbox is necessary to wire-up client-side input and validation functionality.


$(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('Example/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 example 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 = "Example", .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 
    <section name="botDetect" requirePermission="false" 
    type="BotDetect.Configuration.BotDetectConfigurationSection, BotDetect"/>
    <add key="webpages:Version" value="" />
    <add key="webpages:Enabled" value="false" />
    <add key="PreserveLoginUrl" value="true" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    <httpRuntime targetFramework="4.5" />
    <compilation debug="false" targetFramework="4.5" />
    <!-- make sure Session State is enabled -->
    <pages enableSessionState="true">
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
    <!-- 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" />
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,
      dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" 
      responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,
      30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,
      bitness64" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,
      HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.
      TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
      <!-- 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.Mvc" 
        publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="" newVersion="" />
  <botDetect helpLinkEnabled="true" helpLinkMode="image" />

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

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.