Mohamed Farrag
Mohamed Farrag

Reputation: 1692

Recaptcha doesn't work with ajax and partial views

I'm using Recaptcha in my MVC4 web app. It was working correctly when it was embedded in the form but when I moved the @Html.Raw(Html.GenerateCaptchaHelper()) to partial view and trying to call this partial view via ajax request, it doesn't work!

Extension code :

public static string GenerateCaptchaHelper(this HtmlHelper helper)
    {
        var captchaControl = new Recaptcha.RecaptchaControl
        {
            ID = "recaptcha",
            Theme = "clean",
            PublicKey = ************,
            PrivateKey = **********************,
            Language = "En"
        };
        var htmlWriter = new HtmlTextWriter(new StringWriter());
        captchaControl.RenderControl(htmlWriter);
        return htmlWriter.InnerWriter.ToString();
    }

my partial view is has the code like : <p>@Html.Raw(Html.GenerateCaptchaHelper())</p> and inside my controller

public PartialViewResult Captcha()
    {
        return PartialView();
    }

and inside my main view:

 @using (Html.BeginForm("Login", "Account", new { returnUrl = ViewData["ReturnUrl"] }, FormMethod.Post,null))
        {
            @Html.AntiForgeryToken()
            <form role="form">
                <div class="form-group">
                    <label>@Html.LabelFor(m => m.Email)</label><br />
                    @Html.TextBoxFor(m => m.Email, null, new { @class = "form-control", autocomplete = "off" })
                </div>
                <div class="form-group">
                    <label>@Html.LabelFor(m => m.Password)</label><br />
                    @Html.PasswordFor(m => m.Password, new { @class = "form-control", autocomplete = "off" })
                </div>
                <div id="captchaView" class="form-group">
                </div>
                <button type="submit">Login</button>
                    </div>
                </div>
            </form>
        }

and the javascript is :

         $.ajax({
                url: '/Account/Captcha',
                type: 'GET',
                success: function(data) {
                    $('#captchaView').html(data);
                }
            });

Could you please help me to figure out why?

Upvotes: 1

Views: 817

Answers (0)

Related Questions