Question:
I'm saving the data by Ajax, however my reCaptcha is not working correctly, the form is sent even without pressing inside the Captcha.
My Controller
[HttpPost]
[CaptchaValidator(PrivateKey= "secretKey", ErrorMessage="Captcha
Invalido", RequiredMessage ="Campo Obrigatorio")]
public ActionResult SalvarItens(string titulo, string video_url, string
thumb, bool captchaValid)
{
var item = new Dados_Video()
{
Thumb = thumb,
Titulo = titulo,
UrlVideo = video_url
};
db.Dados_Video.Add(item);
db.SaveChanges();
return Json(new { Resultado = item.Id },
JsonRequestBehavior.AllowGet);
}
my view
@using reCAPTCHA.MVC;
<form id="submeter">
<p id="divulgueSeuVideo">Divulgue Seu Vídeo</p><br />
<input type="text" id="titulo" name="titulo" required=""
class="form-control form-home" placeholder="Titulo" /><br />
<input type="url" id="video-url" name="url" required="" class="form-control form-home" placeholder="url" /><br />
<div class="g-recaptcha" data-sitekey="minhaKey"></div>
@Html.ValidationMessage("reCAPTCHA")
<button id="submit" class="btn-block btn-success" onclick="funcaoOnclick();">Enviar Video</button>
</form>
ajax that makes the salute
function SalvarItens() {
var titulo = $("#titulo").val();
var video_url = $("#video-url").val();
var thumb = generateThumb(generateCode(video_url));
var url = "/Home/SalvarItens";
$.ajax({
url: url
, data: {
titulo: titulo, video_url: video_url, thumb: thumb }
, type: "POST"
, datatype: "Json"
, success: function (data) {
if (data.Resultado > 0) {
}
}
});
}
Web.Config
<add key="reCaptchaPublicKey" value="SiteKey" />
<add key="reCaptchaPrivateKey" value="SecretKey" />
Answer:
Since you need to use ajax instead of the standard form submit, a simple way that I see doing this goes like this:
var formData = $('#submeter').serializeArray()[0];
formData.Titulo = $("#titulo").val();
formData.UrlVideo = $("#video-url").val();
formData.Thumb = generateThumb(generateCode(formData.video_url));
var url = "/Home/SalvarItens";
$.ajax({
url: url
, data: formData
, type: "POST"
, datatype: "Json"
, success: function(data) {
if (data.Resultado > 0)
{
}
}
});
This will keep the hash generated by reCaptcha when it is resolved inside the formData
object. With that, the CaptchaValidator
attribute in your action should be able to validate the reCaptcha and the captchaValid
parameter should come with the correct value.
In action, put this code:
[HttpPost]
[CaptchaValidator(PrivateKey= "secretKey", ErrorMessage="Captcha
Invalido", RequiredMessage ="Campo Obrigatorio")]
public ActionResult SalvarItens(Dados_Video item, bool captchaValid)
{
db.Dados_Video.Add(item);
db.SaveChanges();
return Json(new { Resultado = item.Id }, JsonRequestBehavior.AllowGet);
}