reCAPTCHA with ASP.NET MVC 3 RAZOR using Microsoft.Web.Helpers and jQuery

My goal was to put a reCAPTCHA onto my registration page. I’m building the site using ASP.MVC using the Razor view engine.

This is a holy hellish bitch to figure out how to get working the first time with all the conflicting posts from people on it and then of course some of it just straight up doesn’t work because of bugs in how the packages are installed.

Obviously you could just use Javascript and roll your own reCAPTCHA with MVC, but since all these folks have gone to great lengths to figure out how to do this within the MVC Framework using HtmlHelpers and what not you would think I could just throw a few references in and a couple of lines of code and get it going. Why reinvent the wheel right? No, it’s not that simple.

The first page you might have found is this one.

Now it all looks great and probably worked fine with ASP.NET MVC 2, but with Razor all the HTML elements that are output are escaped. So you end up with <script> instead of an actual script tag. I could not for the life of me figure out how to get around this and I’m sure it is something really simple, but there are few detailed syntax references for Razor out there.

So, now I found another page indicating that Microsoft has their own set of Helpers for this and the library can be added using NuGet.

Of course he highlights the System.Web.Helpers library as the one that is added by this package installer when in reality the library doing the work is Microsoft.Web.Helpers so don’t try looking for your helper method in System.Web.Helpers.

The other issue is that the NuGet package installer for microsoft-web-helpers is messed up (as of this writing) and doesn’t install all the references that are required to use it so if you try to run your web site after installing this package you get a lovely yellow screen error.

To solve this you need to follow this fellow’s instructions to add the missing references.

Once you have that done, you can then add

@using Microsoft.Web.Helpers

to the top of your view and then your call to

@ReCaptcha.GetHtml(publicKey:"YOUR KEY", theme: "red")

should work. At least it did for me.

Also, once you get this all done it’s fairly trivial to make this work properly with jQuery. All you need to do is submit the two recaptcha fields to your controller method that is doing your validation along with the rest of your form fields.

$('#FORMID').submit(function (event) {
            if ($(this).valid()) {
                event.preventDefault();
                $.post('/CONTROLLER/ACTION', { recaptcha_challenge_field: $("input#recaptcha_challenge_field").val(), recaptcha_response_field: $("input#recaptcha_response_field").val()},
                function (data) {
                    $('#result').html(data);
                });
            }
        });

Edit: Today (March 1) I found this page that describes the syntax for outputting raw HTML in Razor. Looks like it just got posted a day before I was working on this. Syntax is below in case you wanted to use the code embedded in the ReCaptcha DLL from Google Code.

@Html.Raw(Html.GenerateCaptcha())

I didn’t actually try this out yet, so YMMV.

12 Comments

  1. Thanks for this post. I’ve pi**ed away most of the morning trying to get the new ReCaptcha helper working and only with your help now have it working. Lucky for me I waiting long enough for you to figure this out, since you just posted last night!

  2. Ha, good timing on your part! Took me about three hours of digging through various things that day before I put it all together.

  3. I’ve had mine working well for a while, Thanks. However, now that I’m testing on FireFox, it renders off to the right side of the page. Any thoughts?

  4. Install Firebug and see what the HTML output is showing in Firefox. Try playing with the CSS in Firebug on the fly.

  5. Huh, really I happy I found your post, don’t think I could have figured this out on my own. Thanks!

  6. Thank you. A holy hellish bitch indeed! All sorts of misinformation out there.

    I was trying to get the FileUpload helper working and with the info from this site it is now running. For those with Microsoft Visual Web Deveveloper 2010 SP1, NuGet is integrated under Tools | Library Package Manager.

  7. Ah, I haven’t looked into that in depth, but I’m pretty sure that you use themes to change the appearance. You can pass the theme parameter into the call to @ReCaptcha.GetHtml(). As for creating custom themes that I’m not really sure about.

  8. thanks for your post, however, i am a bit confused regarding what is the final solution as you have provided so many references to other links. Can you also post a complete solution for download?

  9. Thanx for your post, sometimes I feel like its an impossible mission to develop to .Net because of each tool has many changes and even the framework MVC, MVC2, MVC3, Razor in a short period of time. I didn’t get it working even with your post. I have an assembly missing error message when I launch the page. My app finds Microsoft.Web, but it doesn’t find “Helpers”. I’m still working on that. Thank you for your post.

  10. Hey Harvey,

    Good post that helped me start with re-captchas in my first MVC web app. Thanks!

    As for your March 1st edit, you can avoid the messy view code by simply returning the raw string from your GenerateCaptcha extension method already. Make your extension method return an IHtmlString instead of plain string: instead of returning ‘htmlWriter.InnerWriter.ToString();’ make it return ‘helper.Raw(htmlWriter.InnerWriter.ToString());’

    That wraps the string in a class that tells razor not to html encode the output.

    Cheers & happy 2012,
    Ruben

Leave a Reply

Your email address will not be published. Required fields are marked *