Project Description

Assembly for rendering and validating ReCAPTCHA validation for the ASP.NET MVC framework.


RecaptchaMvc comes with a HTML helper to render the correct markup on the page. The Html.Recaptcha method accepts an IRecaptchaModelState that holds the public key and error code (if there is any). Your ViewPage should derive from the generic ViewPage<T> to give the model strongly typed access to IRecaptchaModelState

    public class RecaptchaTest : ViewPage<IRecaptchaModelState>
        //...your code

Then you would use the HTML helper to render the Recaptcha on your page

    <%@ Import Namespace="RecaptchaMvc" %>

    <%=Html.Recaptcha(ViewData.Model) %>

There is multiple overloads for the HTML helper that accept options for Recaptcha like theme, etc. These are injected as javascript into the page for Recaptcha to use.

In your controller, you would instantiate the RecaptchaModelState with the public key for Recaptcha to use and pass it in when you return the view.

    public ActionResult RecaptchaTest() {
        return View(new RecaptchaModelState("publicKey"));

This will give the view the IRecaptchaModelState it needs as its Model to render the Recaptcha control.

When the form is submitted, you would call the TryValidateRecaptcha or ValidateRecaptcha extension methods. Both methods have overloads that accept a private key (uses the DefaultValueProvider), a private key and value provider, or an IRecapthaRequest object that has the data it needs for validation. The TryValidateRecaptcha method returns an IRecaptchaResponse indicating whether validation passed and the error code if validation failed. The ValidateRecaptcha throws an exception when validation fails. If validation fails, you can use the error code to instantiate a new RecaptchaModelState object so the Recaptcha service can retrieve the appropriate error message.

    public ActionResult RecaptchaTest(FromCollection form) {
        IRecaptchaResponse response = TryValidateRecaptcha("privateKey", form);
        if(!response.IsValid) {
            return View(new RecaptchaModelState("publicKey", response.ErrorCode));

Last edited Dec 9, 2008 at 2:45 PM by awilinsk, version 2