Working with Captcha in MVC

Introduction

The following blog provides code snippet about to use of captcha in MVC.

Getting Started

The following source code has been built in MVC5. It uses library from NuGet for captcha control. NuGet provides variety of library for different version of MVC.

For example, for MVC5 NuGet provides library CaptchaMvc5. As I have worked in MVC5, I have downloaded the captchamvc5 library to use in MVC5.
The CaptchaMvc library provides MathCaptcha extended function for displaying captcha in view and captcha can be validate in controller by using IsCaptchaValid extended function which takes string value for displaying validation message in view.

Steps For Use Of Captcha Control In MVC

  1. Download the appropriate captcha library from NuGet. For example, for MVC3 download captcha library CaptchaMvc3
  2. Use ‘CaptchaMvc.HtmlHelpers’ namespace in code behind(controller) and view.
  3. Use the below client code in your view for displaying captcha in view.
  4. Handle the captcha validation in controller, see the below controller code for validation details.
Go through the below code for implementing captcha in MVC.

Client-side code for Captcha.

 @using CaptchaMvc.HtmlHelpers  
 @using CaptchaMvc;  
 @using (Html.BeginForm())  
 {  
   @Html.ValidationSummary(true)  
 <fieldset>  
   @Html.MathCaptcha()  
   @ViewBag.ErrMessage  
   <p>  
     <input type="submit" value="Send" />  
   </p>    
 </fieldset>  
 }  

Server-side code for Captcha.

 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Web;  
 using System.Web.Mvc;  
 using CaptchaMvc.HtmlHelpers;  
 namespace Captcha.Controllers  
 {  
   public class CaptchController : Controller  
   {  
     // GET: Captch  
     public ActionResult Index()  
     {  
       return View();  
     }  
     [HttpPost]  
     public ActionResult Index(string empty)  
     {  
       // Code for validating the CAPTCHA   
       if (this.IsCaptchaValid("Captcha is not valid")==false)  
       {  
         ViewBag.ErrMessage = "Error: captcha is not valid.";  
       }  
       return View();  
     }  
   }  
 }  

Thanks

Kailash Chandra Behera

An IT Professional with 12 years experience in development life cycle in windows, service and Web based application using Microsoft.Net technologies. Proven record of developing all phases of projects in Microsoft.Net technology from initiation to closure aligning with the company's Business objectives to drive process improvements, competitive advantage and bottom-line gains. -> Good exposure of independently working and developing multiple projects ->Committed to efficient and effective development of projects in a fast-paced and deadline driver environment. Skill :- Develop and design projects in various technologies of Microsoft Technology. Total IT Experience- 13+

Previous Post Next Post

نموذج الاتصال