BrunoLM
BrunoLM

Reputation: 100331

How to use @ReCaptcha with Ajax Form in MVC3?

I am trying to use ReCaptcha from Microsoft.Web.Helpers. If I load the entire page it renders correctly, but if I load the page with an ajax request it disappears.

Example (/home/index)

<div id="bla">
    @Ajax.ActionLink("reload with ajax", "index", new AjaxOptions() { UpdateTargetId = "bla" })

    @ReCaptcha.GetHtml(publicKey: "xxx")
</div>

If I enter /home/index the captcha appears. If I click the button reload with ajax the ReCaptcha disappears...

recaptcha

  1. The page is loaded for the first time
  2. reload with ajax was clicked, the contents of the page change to /home/index, in other words, the entire page reloaded asynchronous and the captcha is gone

Is there a way to fix this or a decent captcha helper for MVC 3?

Upvotes: 3

Views: 3806

Answers (2)

user1603729
user1603729

Reputation: 31

I faced the same issue and the quickest solution i found is using what it is proposed above and add to it this part of code in the top of your page within the handler "EndRequestHandler" proposed by the .net javascript api ( http://msdn.microsoft.com/en-us/library/bb311028(v=vs.100)).

With this solution the backend validation always works.

Here is the code I've used :

<script type="text/javascript" language="javascript">
  Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
  function EndRequestHandler(sender, args) {
            if (Recaptcha != null) {
                     Recaptcha.destroy();
                     Recaptcha.create("public_key", "captcha", {});
                  }
              }
</script>

I hope this could help someone...

Upvotes: 3

BrunoLM
BrunoLM

Reputation: 100331

I've replaced the helper with javascript. ReCaptcha script

<div id="captcha"></div>

<input type="submit" value="Send" />

<script type="text/javascript">
Recaptcha.destroy();
Recaptcha.create("publicKey", "captcha", {});
</script>

And the Controller is still the same

if (ReCaptcha.Validate("privateKey"))
{
}

So when it loads the view partially it executes this scripts and render correctly every time.

Thanks for the help @Bala R

Upvotes: 4

Related Questions