Automatically reload reCAPTCHA when postingback via a partial refresh (UpdatePanel)

So, today, i wanted to use reCAPTCHA. Since this is an online service I was a bit skeptical at first with regard to downtime. However their faq states the following :

reCAPTCHA has distributed locations and multiple servers.

 With that, we know that the service should be available pretty much all the time. And honestly, if it's good enough to service facebook's massive user base, it's good enough for me. Fact is, many people are already familiar with the service and know what to expect and how to proceed. However, the deciding factor was the noble cause of this project. Basically for every captcha that is deciphered, you are actually helping decode a word in a book that was digitized for the public domain by volunteers using OCR(optical character reconigition). Sometimes there are a few words that an OCR cannot read and these are the words presented in the catpcha. So while fighting spam, you are actually helping digitize books. Brilliant! I was sold :P:P

If your looking to using this captcha service, then, after signing up to the service on their site ReCAPTCHA , you shall be provided with a public/private key to access the service. And this is all you need, since they already have a custom web control that you can insert into your asp.net pages to communicate with their service and consume the captcha. You can inform yourself more about how to consume it from your webform pages here : reCAPTCHA AND ASP.NET

Now, while this is all working nicely, getting it to play nice with the UpdatePanel might be difficult for some. I say that because i have read a few articles online with workarounds, when there was no need. So the goal here is to have the captcha automatically refresh itself, if the captcha words submitted were wrong. So lets see how to do just that :

First, what you want to do is make sure that the UpdateMode for the updatepanel is set to conditional. This means, you are responsible for calling update on the updatepanel manually. We want to make this manual because if the captcha is invalid, then you do not want the updatepanel containing the captcha to refresh(this will only make recaptcha dissappear). Instead, we add a second updatepanel. Code speaks a thousand words, so lets take a look at functional code :

 <form runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" ChildrenAsTriggers="false"
UpdateMode="Conditional"
runat="server">
<ContentTemplate>
<asp:TextBox ID="TextBoxComment" TextMode="MultiLine" Rows="5"
Columns="35" runat="server"></asp:TextBox>
<recaptcha:RecaptchaControl ID="recaptcha1" runat="server"
Theme="red" PublicKey="6LcBAAAAAAAAAKtzVYRsIgOAAvCFge3iiMtf6hI9"
PrivateKey="6LcBAAAAAAAAACQnFb_BI5tX7OxqC-C5RtROzx-S" />
<asp:UpdatePanel ID="UpdatePanel2"
ChildrenAsTriggers="false" UpdateMode="Conditional"
runat="server">
<ContentTemplate>
<asp:Label ID="labelError"
runat="server" EnableViewState="false" />
</ContentTemplate>
</asp:UpdatePanel>
<br />
<asp:Button ID="btnSubmit" ValidationGroup="GroupName"
runat="server" Text="Submit" OnClick="btnSubmit_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</form>

As you can note from the code above, we have two updatepanels. The second updatepanel contains a label to tell the user that the text they submitted is wrong. This is the only updatepanel we want to refresh when the captcha submitted is invalid.

Now the minimum c# code to do our bidding : 

void btnSubmit_Click(object sender, EventArgs args)
{
if (!recaptcha1.IsValid)
{
labelError.Text = "Incorrect, try again!";
labelError.ForeColor = System.Drawing.Color.Red;
//Reload recaptcha
ScriptManager.RegisterClientScriptBlock(this.Page,
this.Page.GetType(), "whatever1",
"Recaptcha.reload();", true);
UpdatePanel2.Update();
}
}

As you can note from above, the main code of interest here is the code we are registering via the ScriptManager, specifically -> "Recaptcha.reload(); what this will do is reload the captcha on the clientside when the second updatepanel refreshes whilst display an error message to our clients telling them to retry the captcha. I would love to make this article longer than it already is, however that's about it :-)

Screen shots of what it looks like before we submit and what it looks like after below :

 

After : note how the captcha is successfully reloaded via a partial postback.

Update 26-september-2008 : The full source to the example code i have used throughout this posting :

<%@ Page Language="C#" %>
<%@ Register TagPrefix="recaptcha" 
Namespace="Recaptcha" Assembly="Recaptcha" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
void btnSubmit_Click(object sender, EventArgs args)
{
    if (!recaptcha1.IsValid)
    {
        labelError.Text = "Incorrect, try again!";
        labelError.ForeColor = System.Drawing.Color.Red;
        //Reload recaptcha
        ScriptManager.RegisterClientScriptBlock(this.Page,
    this.Page.GetType(), "whatever1",
        "Recaptcha.reload();", true);
        UpdatePanel2.Update();
    }
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="Form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" ChildrenAsTriggers="false" 
UpdateMode="Conditional"
    runat="server">
    <ContentTemplate>
        <asp:TextBox ID="TextBoxComment" TextMode="MultiLine" Rows="5"
Columns="35" runat="server"></asp:TextBox>
        <recaptcha:RecaptchaControl ID="recaptcha1" runat="server" 
Theme="red" PublicKey="6LcBAAAAAAAAAKtzVYRsIgOAAvCFge3iiMtf6hI9"
            PrivateKey="6LcBAAAAAAAAACQnFb_BI5tX7OxqC-C5RtROzx-S" />
        <asp:UpdatePanel ID="UpdatePanel2" 
ChildrenAsTriggers="false" UpdateMode="Conditional"
            runat="server">
            <ContentTemplate>
                <asp:Label ID="labelError" 
runat="server" EnableViewState="false" />
            </ContentTemplate>
    </asp:UpdatePanel>
    <br />
    <asp:Button ID="btnSubmit" ValidationGroup="GroupName" 
runat="server" Text="Submit" OnClick="btnSubmit_Click" />
    </ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>

 

Published Tuesday, September 09, 2008 9:03 AM by alessandro
Filed under: , ,

Comments

# re: Automatically reload reCAPTCHA when postingback via a partial refresh (UpdatePanel)

Thursday, September 25, 2008 1:46 PM by Aaron

Hmmm.  This all makes sense, but I get an:

Error: 'null' is null or not an object

when I try to submit with an invalid entry in the reCaptcha...

# re: Automatically reload reCAPTCHA when postingback via a partial refresh (UpdatePanel)

Friday, September 26, 2008 9:02 AM by alessandro

hi Aron, unfortunately that didn't make any sense. I'm including the full source i used throughout this post above, in the hopes that it may help you further.

Good luck :-)

# re: Automatically reload reCAPTCHA when postingback via a partial refresh (UpdatePanel)

Wednesday, December 03, 2008 9:48 AM by denniscy

Thank you, very useful.

# re: Automatically reload reCAPTCHA when postingback via a partial refresh (UpdatePanel)

Sunday, December 07, 2008 11:32 PM by Anonymouse

alessandro, thank you so much for sharing your solution. It wasn't working at first, but after adding ChildrenAsTriggers="false" it worked perfectly!

# re: Automatically reload reCAPTCHA when postingback via a partial refresh (UpdatePanel)

Friday, December 12, 2008 2:48 PM by Javier

Alessandro, what can I do if my Recaptcha is inside a MultiView which is encapsulated by a UpdatePanel?  I applied your solution with no results. Thanks.

# re: Automatically reload reCAPTCHA when postingback via a partial refresh (UpdatePanel)

Friday, December 12, 2008 4:01 PM by alessandro

hi Javier, it would be faster to test your issue at hand if you can post some pseudocode, that way i know exactly under what condition it's failing.

# re: Automatically reload reCAPTCHA when postingback via a partial refresh (UpdatePanel)

Thursday, December 18, 2008 8:30 AM by Toby

Hi,

Example works ok however it never returns a valid response. if the update panels are removed it works. any ideas?

regards

toby.

# re: Automatically reload reCAPTCHA when postingback via a partial refresh (UpdatePanel)

Monday, March 02, 2009 3:50 PM by Ben

Calling the Validate method fixes the failure ti validate:

public void btnSubmit_Click(object sender, EventArgs args)

{

   recaptcha1.Validate();

   if (!recaptcha1.IsValid)

   {

       labelError.Text = "Incorrect, try again!";

labelError.ForeColor = System.Drawing.Color.Red;

//Reload recaptcha

ScriptManager.RegisterClientScriptBlock(

this.Page,

this.Page.GetType(),

"whatever1",

"Recaptcha.reload();",

true);

       UpdatePanel2.Update();

   }

}

# The ASP.NET Capsule #5: Adding Captcha to your web forms

Tuesday, May 12, 2009 10:59 PM by Jose R. Guay Paz

Hi all. I was asked to add captcha to some web forms for contact and subscription information, so I though

# re: Automatically reload reCAPTCHA when postingback via a partial refresh (UpdatePanel)

Friday, June 12, 2009 5:08 AM by Shriram

Hello ,

I read above comments. Also I m getting same problem .

do need to add

" ScriptManager.RegisterClientScriptBlock(

this.Page,

this.Page.GetType(),

"whatever1",

"Recaptcha.reload();",

true);"

only you can update your update your update panel.

problem will solved.

Thanks

# re: Automatically reload reCAPTCHA when postingback via a partial refresh (UpdatePanel)

Friday, June 12, 2009 6:12 AM by henry

I have copied this, however it always returns false, even if i type in the words correctly.?!

any help?

thanks

# re: Automatically reload reCAPTCHA when postingback via a partial refresh (UpdatePanel)

Sunday, July 26, 2009 4:08 PM by Phil

I second Henrys problem. IT always returns false. Any solutions?

# re: Automatically reload reCAPTCHA when postingback via a partial refresh (UpdatePanel)

Sunday, July 26, 2009 4:39 PM by Phil

Actually, I take it back. It doesn't return false, rather, nothing at all happens. I added the following to the code-behind:

if (recaptcha1.IsValid)

       {

           labelError.Text = "Great!";

           labelError.ForeColor = System.Drawing.Color.Green;

       }

but as mentioned, the code doesn't execute??

# Automatically reload reCAPTCHA when postingback via a partial refresh (UpdatePanel) &laquo; Yasserzaid&#8217;s Weblog

Pingback from  Automatically reload reCAPTCHA when postingback via a partial refresh (UpdatePanel)  &laquo; Yasserzaid&#8217;s Weblog

# re: Automatically reload reCAPTCHA when postingback via a partial refresh (UpdatePanel)

Friday, September 04, 2009 10:11 AM by narinder

I download your .dll file but its refference is not added  into asp page . please tell me how we can add refference in asp.net.

thanks for helf

# re: Automatically reload reCAPTCHA when postingback via a partial refresh (UpdatePanel)

Friday, September 25, 2009 6:24 PM by Filipp

Thank you!  Just what I was looking for!

Leave a Comment

(required) 
(required) 
(optional)
(required)