Saturday, 12 July 2014

Spam Control : Apply CAPTCHA in ASP.NET MVC 4 Step by Step

I am here to tell how you can put CAPTCHA image inside your form. It is very easy in ASP.NET MVC 4 With NuGet.
Step 1:
Open your Visual Studio and select your project in which you want to work.

Step 2:
Go to Tools In Menu Bar > Library Package Manager > Package Manager Console.
Step 3:
Write this command in Package Manager Console

Install-Package Captcha
 
Step 4:
Open the form where you want to put CAPTCHA:

Step 5:
Include this name space at the top of the page
@using BotDetect.Web.UI.Mvc;

Step 6:
Write this code in the head section of your page
<link href="@BotDetect.Web.CaptchaUrls.Absolute.LayoutStyleSheetUrl" rel="stylesheet" type="text/css" />

Note: If you are using Layout then add above code to the layout page.

Step 7:
Write this code at your form page where you want to display CAPTCHA image
<div class="block">
            @{ MvcCaptcha sampleCaptcha = new MvcCaptcha("SampleCaptcha"); }
@Html.Captcha(sampleCaptcha)
            @Html.Label("Enter above Characters")
@Html.TextBox("CaptchaCode")
        </div>

Step 8:
Now its time to work in controller
Open respective controller > Seek the required action (Post such as register ) and put this code (Put Green color line code before your action method)
[HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        [CaptchaValidation("CaptchaCode", "SampleCaptcha", "Incorrect CAPTCHA code!")]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                try
                {
                    WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
                    WebSecurity.Login(model.UserName, model.Password);
                    return RedirectToAction("Index", "Home");
                }
                catch (MembershipCreateUserException e)
                {
                    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

I am take the example of MVC4 Register controller.

Step 9 :
Now you have to include name space at the top of your controller

using BotDetect.Web.UI.Mvc;

Step 10:
Last Step to show message at view, Put the following line of code inside your form
@Html.ValidationSummary()

Work is done . Enjoy
Feel free to query....