Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Alistair Jenkins 92 posts 315 karma points
    Mar 23, 2018 @ 15:51
    Alistair Jenkins
    0

    reCaptcha not recognising successful response

    Hi,

    I have added reCaptcha V2 to my working contact form as per this blog entry. However when I try to submit the form with the reCaptcha successfully completed I get the "Please complete the reCAPTCHA" error message which is thrown when the response is null or empty. Here are my model, view and controller with the code from the site added.

    ContactFormViewModel.cs

    using System.ComponentModel.DataAnnotations;
    
    namespace ContactForm.Models
    {
    public class ContactFormViewModel
    {
        public string Name { get; set; }
    
        [Required(ErrorMessage = "Please enter your email")]
        [EmailAddress(ErrorMessage = "The email given is not a valid email address. Please try again.")]
        public string Email { get; set; }
    
        public string Subject { get; set; }
    
        public string Message { get; set; }
    }
    }
    

    ContactUsPage2.cshtml

    @using Recaptcha.Web.Mvc
    @inherits Umbraco.Web.Mvc.UmbracoTemplatePage
    @{
    Layout = "layoutTemplate2.cshtml";
    }
    
    <div class="centre">
    <div id="contactForm">
        @Html.Action("ContactForm", "ContactForm")
    </div>
    <div id="contactFormBlurb">
        <p>@Umbraco.Field("contactFormMessage", recursive: true)</p>
    </div>
    <div id="reCaptcha">
        @Html.Recaptcha(theme: Recaptcha.Web.RecaptchaTheme.Clean)
    </div>
    
    </div>
    

    ContactFormController.cs

    using ContactForm.Models;
    using System.Net.Mail;
    using System.Web.Mvc;
    using Umbraco.Web;
    using Umbraco.Web.Mvc;
    using Recaptcha.Web;
    using Recaptcha.Web.Mvc;
    
    namespace ContactForm.Controllers
    {
    public class ContactFormController : SurfaceController
    {
        [HttpPost]
        public ActionResult SendMail(ContactFormViewModel model)
        {
    
            if (!ModelState.IsValid)
            {
                return CurrentUmbracoPage();
            }
    
            RecaptchaVerificationHelper recaptchaHelper = this.GetRecaptchaVerificationHelper();
            if (string.IsNullOrEmpty(recaptchaHelper.Response))
            {
                ModelState.AddModelError("reCAPTCHA", "Please complete the reCAPTCHA");
                return CurrentUmbracoPage();
            }
            else
            {
                RecaptchaVerificationResult recaptchaResult = recaptchaHelper.VerifyRecaptchaResponse();
                if (recaptchaResult != RecaptchaVerificationResult.Success)
                {
                    ModelState.AddModelError("reCAPTCHA", "The reCAPTCHA is incorrect");
                    return CurrentUmbracoPage();
                }
            }
    
            if (ModelState.IsValid)
            {
                return SendMessage(model);
            }
    
            return RedirectToCurrentUmbracoPage();
        }
    
        private ActionResult SendMessage(ContactFormViewModel model)
        {
    
            string str = $"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd \"><html xmlns=\"http://www.w3.org/1999/xhtml \"><head></head><body><p>Name: {model.Name}</p> <p>Email: {model.Email}</p> <p>Message: {model.Message}</p></body></html>";
            string sub = $"{model.Subject}";
            string emailto = CurrentPage.GetPropertyValue<string>("emailAddressTo");
    
            MailMessage msg = new MailMessage();
    
            msg.From = new MailAddress("[email protected]");
            msg.To.Add(emailto);
            msg.Subject = sub;
            msg.Body = str;
            msg.Priority = MailPriority.Normal;
            msg.IsBodyHtml = true;
    
            SmtpClient client = new SmtpClient();
    
            client.Send(msg);
            TempData.Add("Success", value: "Your message was successfully sent.");
            TempData.Add("GetBack", value: "We will get back to you as soon as possible.");
            return Redirect();
        }
    
        private ActionResult Redirect() => RedirectToCurrentUmbracoPage();
    
        public ActionResult ContactForm() { return PartialView(""); }
    }
    }
    

    If anyone can shed light on why this isn't working, I'd be grateful.

    Thanks, Alistair

  • Paul Seal 524 posts 2889 karma points MVP 7x c-trib
    Mar 23, 2018 @ 16:52
    Paul Seal
    0

    Here is what I did on my most recent project:

    using System.Web.Mvc;
    using Umbraco.Web.Mvc;
    using ContactForm.Models;
    using System.Net.Mail;
    using log4net;
    using System.Reflection;
    using Recaptcha.Web;
    using Recaptcha.Web.Mvc;
    
    namespace ContactForm.Controllers
    {
        public class ContactFormController : SurfaceController
        {
            public string GetViewPath(string name)
            {
                return string.Format("/Views/Partials/Contact/{0}.cshtml", name);
            }
    
            [HttpGet]
            public ActionResult RenderForm()
            {
                ContactViewModel model = new ContactViewModel();
                return PartialView(GetViewPath("_ContactForm"), model);
            }
    
            [HttpPost]
            public ActionResult RenderForm(ContactViewModel model)
            {
                return PartialView(GetViewPath("_ContactForm"), model);
            }
    
            [HttpPost]
            public ActionResult SubmitForm(ContactViewModel model)
            {
                RecaptchaVerificationHelper recaptchaHelper = this.GetRecaptchaVerificationHelper();
                if (string.IsNullOrEmpty(recaptchaHelper.Response))
                {
                    ModelState.AddModelError("reCAPTCHA", "Please complete the reCAPTCHA");
                    return CurrentUmbracoPage();
                }
                else
                {
                    RecaptchaVerificationResult recaptchaResult = recaptchaHelper.VerifyRecaptchaResponse();
                    if (recaptchaResult != RecaptchaVerificationResult.Success)
                    {
                        ModelState.AddModelError("reCAPTCHA", "The reCAPTCHA is incorrect");
                        return CurrentUmbracoPage();
                    }
                }
    
                bool success = false;
                if (ModelState.IsValid)
                {
                    success = SendEmail(model);
                    TempData["FormResult"] = success;
                    return RedirectToCurrentUmbracoPage();
                }
                return CurrentUmbracoPage();   
            }
    
            public bool SendEmail(ContactViewModel model)
            {
                //send the email
            }
        }
    }
    
  • Alistair Jenkins 92 posts 315 karma points
    Mar 23, 2018 @ 17:03
    Alistair Jenkins
    0

    Hi Paul,

    Thanks for this. Sadly I have to head home now, but I'll pick this up next Friday when I'm back in.

    Cheers, Alistair

  • Alistair Jenkins 92 posts 315 karma points
    Mar 30, 2018 @ 10:18
    Alistair Jenkins
    0

    Hi,

    Back in now, and I've been trying to get this to work and in my attempts to get round various errors have ended up with the following:

    ContactFormViewModel.cs

    using System.ComponentModel.DataAnnotations;
    
    namespace ContactFormView.Models
    {
    public class ContactFormViewModel
    {
        public string Name { get; set; }
    
        [Required(ErrorMessage = "Please enter your email")]
        [EmailAddress(ErrorMessage = "The email given is not a valid email address. Please try again.")]
        public string Email { get; set; }
    
        public string Subject { get; set; }
    
        public string Message { get; set; }
    }
    }
    

    ContactFormSurfaceController.cs

    using ContactFormView.Models;
    using System.Net.Mail;
    using System.Web.Mvc;
    using Umbraco.Web;
    using Umbraco.Web.Mvc;
    using Recaptcha.Web;
    using Recaptcha.Web.Mvc;
    
    namespace ContactFormView.Controllers
    {
    public class ContactFormSurfaceController : SurfaceController
    {
        public string GetViewPath(string name)
        {
            return string.Format("/Views/{0}.cshtml", name);
        }
    
        [HttpGet]
        public ActionResult RenderForm()
        {
            ContactFormViewModel model = new ContactFormViewModel();
            return PartialView(GetViewPath("ContactUsPage2"), model);
        }
    
        [HttpPost]
        public ActionResult RenderForm(ContactFormViewModel model)
        {
            return PartialView(GetViewPath("ContactUsPage2"), model);
        }
    
        [HttpPost]
        public ActionResult SubmitForm(ContactFormViewModel model)
        {
            RecaptchaVerificationHelper recaptchaHelper = this.GetRecaptchaVerificationHelper();
            if (string.IsNullOrEmpty(recaptchaHelper.Response))
            {
                ModelState.AddModelError("reCAPTCHA", "Please complete the reCAPTCHA");
                return CurrentUmbracoPage();
            }
            else
            {
                RecaptchaVerificationResult recaptchaResult = recaptchaHelper.VerifyRecaptchaResponse();
                if (recaptchaResult != RecaptchaVerificationResult.Success)
                {
                    ModelState.AddModelError("reCAPTCHA", "The reCAPTCHA is incorrect");
                    return CurrentUmbracoPage();
                }
            }
    
            bool success = false;
            if (ModelState.IsValid)
            {
                success = SendEmail(model);
                TempData["FormResult"] = success;
                return RedirectToCurrentUmbracoPage();
            }
            return CurrentUmbracoPage();
        }
    
        public bool SendEmail(ContactFormViewModel model)
        {
            string str = $"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd \"><html xmlns=\"http://www.w3.org/1999/xhtml \"><head></head><body><p>Name: {model.Name}</p> <p>Email: {model.Email}</p> <p>Message: {model.Message}</p></body></html>";
            string sub = $"{model.Subject}";
            string emailto = CurrentPage.GetPropertyValue<string>("emailAddressTo");
    
            MailMessage msg = new MailMessage();
    
            msg.From = new MailAddress("[email protected]");
            msg.To.Add(emailto);
            msg.Subject = sub;
            msg.Body = str;
            msg.Priority = MailPriority.Normal;
            msg.IsBodyHtml = true;
    
            SmtpClient client = new SmtpClient();
    
            client.Send(msg);
            TempData.Add("Success", value: "Your message was successfully sent.");
            TempData.Add("GetBack", value: "We will get back to you as soon as possible.");
            return true;
        }
    }
    }
    

    ContactUsPage2.cshtml

    @using Recaptcha.Web.Mvc
    @inherits Umbraco.Web.Mvc.UmbracoTemplatePage
    @{
    Layout = "layoutTemplate2.cshtml";
    }
    
    <div class="centre">
    <div id="contactForm">
        @Html.Action("RenderForm", "ContactFormSurface")
    </div>
    <div id="contactFormBlurb">
        <p>@Umbraco.Field("contactFormMessage", recursive: true)</p>
    </div>
    <div id="reCaptcha">
        @Html.Recaptcha(theme: Recaptcha.Web.RecaptchaTheme.Clean) 
    </div>
    
    </div>
    

    But on loading the page I get this error

    Cannot bind source type ContactFormView.Models.ContactFormViewModel to model type Umbraco.Web.Models.RenderModel.

  • Alistair Jenkins 92 posts 315 karma points
    Apr 13, 2018 @ 08:45
    Alistair Jenkins
    0

    Hi,

    Is there nobody who can shed light on this for me?

    Yours hopefully, Alistair

  • Marc Love (uSkinned.net) 447 posts 1789 karma points
    Apr 13, 2018 @ 09:18
    Marc Love (uSkinned.net)
    0

    Hi Alistair,

    Without the use of your helper library there is another way to achieve this functionality.

    Within your webpage head section you will need:

    <script src='https://www.google.com/recaptcha/api.js'></script>
    

    On your form make sure you have the following HTML:

    <div class="g-recaptcha" data-sitekey="YOUR SITE KEY HERE"></div>
    

    Within your form submission method add the following:

    var response = Request["g-recaptcha-response"];
    string secretKey = YOUR SECRET KEY HERE;
    var client = new WebClient();
    var result = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secretKey, response));
    var obj = JObject.Parse(result);
    var status = (bool)obj.SelectToken("success");
    
    if(!status)
    {
        //ADD CODE HERE THAT YOU WANT TO HAPPEN IF THE CAPTCHA FAILS
    }
    
  • Alistair Jenkins 92 posts 315 karma points
    Apr 13, 2018 @ 12:36
    Alistair Jenkins
    0

    Hi Marc,

    Well, I've tried implementing your code. I went back to the first version I had, to avoid the problems with RenderForm() I was having in the second version. I put in the script and div tags where you suggested and altered my controller to the code below:

    using ContactFormView.Models;
    using System.Net.Mail;
    using System.Web.Mvc;
    using Umbraco.Web;
    using Umbraco.Web.Mvc;
    using Newtonsoft.Json.Linq;
    
    namespace ContactFormView.Controllers
    {
    public class ContactFormSurfaceController : SurfaceController
    {
        [HttpPost]
        public ActionResult SendMail(ContactFormViewModel model)
        {
    
            if (!ModelState.IsValid)
            {
                return CurrentUmbracoPage();
            }
            else
            {
                var response = Request["g-recaptcha-response"];
                string secretKey = "my private key";
                var client = new System.Net.WebClient();
                var result = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secretKey, response));
                var obj = JObject.Parse(result);
                var status = (bool)obj.SelectToken("success");
    
                if (!status)
                {
                    ModelState.AddModelError("reCAPTCHA", "The reCAPTCHA is incorrect");
                    return CurrentUmbracoPage();
                }
                else
                {
                    return SendMessage(model);
                }
            }
        }
    
        private ActionResult SendMessage(ContactFormViewModel model)
        {
    
            string str = $"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd \"><html xmlns=\"http://www.w3.org/1999/xhtml \"><head></head><body><p>Name: {model.Name}</p> <p>Email: {model.Email}</p> <p>Message: {model.Message}</p></body></html>";
            string sub = $"{model.Subject}";
            string emailto = CurrentPage.GetPropertyValue<string>("emailAddressTo");
    
            MailMessage msg = new MailMessage();
    
            msg.From = new MailAddress("[email protected]");
            msg.To.Add(emailto);
            msg.Subject = sub;
            msg.Body = str;
            msg.Priority = MailPriority.Normal;
            msg.IsBodyHtml = true;
    
            SmtpClient client = new SmtpClient();
    
            client.Send(msg);
            TempData.Add("Success", value: "Your message was successfully sent.");
            TempData.Add("GetBack", value: "We will get back to you as soon as possible.");
            return Redirect();
        }
    
        private ActionResult Redirect() => RedirectToCurrentUmbracoPage();
    
        public ActionResult ContactForm() { return PartialView("ContactUsPage2"); }
    }
    }  
    

    But now the page just hangs on loading. It never loads and it never throws an error. Any idea why?

    Cheers, Alistair

  • Marc Love (uSkinned.net) 447 posts 1789 karma points
    Apr 13, 2018 @ 12:43
    Marc Love (uSkinned.net)
    0

    Hi Alistair,

    Have you tried stepping through your code with debugger to see what part is hanging?

    Cheers,

    Marc

  • Alistair Jenkins 92 posts 315 karma points
    Apr 13, 2018 @ 12:48
    Alistair Jenkins
    0

    Hi Marc,

    Do you mean in Visual Studio. I'm fairly new to VS so it's not something I've tried before, but I'll try that and see how I go.

    Cheers, Alistair

  • Alistair Jenkins 92 posts 315 karma points
    Apr 13, 2018 @ 12:57
    Alistair Jenkins
    0

    Hi Marc,

    OK, The

    @Html.Action("ContactForm", "ContactFormSurface")
    

    in my partial view threw an unhandled exception

    System.StackOverflowException
      HResult=0x800703E9
      Source=<Cannot evaluate the exception source>
      StackTrace:
     <Cannot evaluate the exception stack trace>
    

    so I think I had created a loop with

     public ActionResult ContactForm() { return PartialView("ContactUsPage2"); }
    

    which was the result of hacking about to try and solve a previous problem.

    So I've changed the @Html.Action to

    @Html.Action("SendMail", "ContactFormSurface")
    

    But now I get the error

    A public action method 'SendMail' was not found on controller 'ContactFormView.Controllers.ContactFormSurfaceController'.

    But I have this in my controller

     [HttpPost]
     public ActionResult SendMail(ContactFormViewModel model)
    

    Is that not a public action method called SendMail?

  • Marc Love (uSkinned.net) 447 posts 1789 karma points
    Apr 13, 2018 @ 12:54
    Marc Love (uSkinned.net)
    0

    You should add a break point to the first line of your method. Then run debugger to step through each line of code. You will be able to see where it is hanging.

  • Alistair Jenkins 92 posts 315 karma points
    Apr 13, 2018 @ 15:58
    Alistair Jenkins
    0

    Hi Marc,

    Right. I've finally sorted out the @Html.Action problem and the reason for it is too embarrasing an error to repeat here, especially as it doesn't relate to the initial topic of the post. Suffice to say that my form now displays as before, with the reCaptcha at the bottom. However, I still have the same problem with your solution, ie It doesn't matter if I check the reCaptcha or not, clicking the send button results in the message "The reCaptcha is not correct" and no email is sent. Any ideas?

    Cheers, Alistair

  • Lewis Smith 211 posts 620 karma points c-trib
    Apr 13, 2018 @ 16:19
    Lewis Smith
    0

    Hi Alistair,

    I'm rushed for time but i thought i would share my code to see if it helps you around the problem as i have implemented recaptcha many times using the same methods!

    Form in view:

    @using Recaptcha.Web.Mvc;
    @inherits UmbracoViewPage<web.Models.ContactModel>
    @using (Html.BeginUmbracoForm("SendForm", "Contact", FormMethod.Post, new { @class = "contact-form" }))
    {
        <input type="hidden" name="SubmissionPage" value="@HttpContext.Current.Request.Url.AbsoluteUri" />
            @Html.AntiForgeryToken()            
            <div class="form-item">
                @Html.Recaptcha(theme: Recaptcha.Web.RecaptchaTheme.Clean)
            </div>
            <div class="form-item">
                <button>Submit</button>
            </div>
    }
    

    This submits to the controller of 'ContactController' to the method of 'SendForm'

    public ActionResult SendForm(ContactModel Model)
            {
                var response = Request["g-recaptcha-response"];
                if (string.IsNullOrEmpty(response))
                {
                    return RedirectToUmbracoPage(FailedId);
                }
                var secretKey = ConfigurationManager.AppSettings["recaptchaPrivateKey"].ToString();
                var client = new WebClient();
                var result = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secretKey, response));
                var obj = JObject.Parse(result);
                var status = (bool)obj.SelectToken("success");
                if (!status)
                {
                    return RedirectToUmbracoPage(FailedId);
                }
                //Google recaptcha must be valid to reach this far
                if (ModelState.IsValid)
                {
                   //send form magic
                }
                else
                {
                    return RedirectToUmbracoPage(FailedId);
                }
            }
    

    Although i have missed parts out hopefully this will help!

    Let me know if you have any more issues questions!

    /Lewis

  • Alistair Jenkins 92 posts 315 karma points
    Apr 20, 2018 @ 13:04
    Alistair Jenkins
    0

    Hi,

    I managed to work out how to capture the error code from reCaptcha and it was:

    missing-input-response - The response parameter is missing

    Below is the latest version of my controller, hacked about in an attempt to get the error-codes. Can anybody tell me why the response isn't getting passed to Google? I haven't included the SendMessage() section as it remains the same as before. SendMail() is what's being called initially.

    using ContactFormView.Models;
    using System.Net.Mail;
    using System.Web.Mvc;
    using Umbraco.Web;
    using Umbraco.Web.Mvc;
    using Newtonsoft.Json;
    using System.Collections.Generic;
    using System;
    using System.Diagnostics;
    using System.IO;
    using System.Text;
    
    namespace ContactFormView.Controllers
    {
    public class ContactFormSurfaceController : SurfaceController
    {
    
        public class ReCaptchaClass
        {
            public static string Validate(string EncodedResponse)
            {
                var client = new System.Net.WebClient();
    
                string PrivateKey = "6LfLjxcUAAAAAD3uofXIL0Evj8G3LgG5T04oz3RD";
    
                var GoogleReply = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", PrivateKey, EncodedResponse));
    
                var captchaResponse = JsonConvert.DeserializeObject<ReCaptchaClass>(GoogleReply);
    
                var errorlist = captchaResponse.ErrorCodes;
    
                if (errorlist.Count != 0)
                {
                    Console.SetOut(new DebugTextWriter());
                    errorlist.ForEach(Console.WriteLine);
                }
                else
                {
                    Console.SetOut(new DebugTextWriter());
                    Console.WriteLine("No errors from reCaptcha");
                }
    
                return captchaResponse.Success;
            }
    
            [JsonProperty("success")]
            public string Success
            {
                get { return m_Success; }
                set { m_Success = value; }
            }
    
            private string m_Success;
    
            [JsonProperty("error-codes")]
            public List<string> ErrorCodes
            {
                get { return m_ErrorCodes; }
                set { m_ErrorCodes = value; }
            }
    
    
            private List<string> m_ErrorCodes;
    
        }
    
        [HttpPost]
        public ActionResult SendMail(ContactFormViewModel model)
        {
    
            if (!ModelState.IsValid)
            {
                return CurrentUmbracoPage();
            }
            else
            {
                string EncodedResponse = Request.Form["g-Recaptcha-Response"];
                bool IsCaptchaValid = (ReCaptchaClass.Validate(EncodedResponse) == "true" ? true : false);
    
                if (!IsCaptchaValid)
                {
                    ModelState.AddModelError("reCAPTCHA", "The reCAPTCHA is incorrect");
                    return CurrentUmbracoPage();
                }
                else
                {
                    return SendMessage(model);
                }
            }
        }
    
  • Alistair Jenkins 92 posts 315 karma points
    Apr 20, 2018 @ 13:46
    Alistair Jenkins
    0

    Got it! It wasn't a problem with the controller at all. The div containing the reCaptcha was on the partial view that called the form using the @Html.Action rather than on the form view itself. So

    string EncodedResponse = Request.Form["g-Recaptcha-Response"];
    

    couldn't find the g-recaptcha-response textarea where the response is stored.

    Now I've got a separate problem that the email sends ok but I get a YSOD rather than being redirected to the current page. But that's for another thread. Hope it doesn't take as long to work out!

    Thanks for all the help.

    Cheers, Alistair

  • Arther 3 posts 73 karma points notactivated
    Mar 17, 2020 @ 15:21
    Arther
    0

    Hi Gurus,

    I am so frustrated with this reCAPTCHA V2 using MVC in Umbraco v8.x.x. It does not check or validate recaptcha at all. It simply submit the form with no message. Please help.

    I used recent latest video of creating Contact form and client dependency Umbraco v8 on youtube, When i submit the form it doesn't validate the Recaptha field.

    using Project.Core.Services;
    using Project.Core.ViewModels;
    using Recaptcha.Web;
    using Recaptcha.Web.Mvc;
    using System.Web;
    using System.Web.Mvc;
    using Umbraco.Web;
    using Umbraco.Web.Mvc;
    
    namespace Project.Core.Controllers
    {
        public class ContactSurfaceController : SurfaceController
        {
            private readonly ISmtpService _smtpService;
    
            public ContactSurfaceController(ISmtpService smtpService)
            {
                _smtpService = smtpService;
            }
    
            [HttpGet]
            public ActionResult RenderForm()
            {
                ContactViewModel model = new ContactViewModel() { ContactFormId = CurrentPage.Id };
                return PartialView("~/Views/Partials/Contact/contactForm.cshtml", model);
            }
    
            [HttpPost]
            public ActionResult RenderForm(ContactViewModel model)
            {
                return PartialView("~/Views/Partials/Contact/contactForm.cshtml", model);
            }
    
            [HttpPost]
            public ActionResult SubmitForm(ContactViewModel model)
            {
    
                if (!ModelState.IsValid)
                {
                    return CurrentUmbracoPage();
    
                }
    
                RecaptchaVerificationHelper recaptchaHelper = this.GetRecaptchaVerificationHelper();
                if (string.IsNullOrEmpty(recaptchaHelper.Response))
                {
                    ModelState.AddModelError("reCAPTCHA", "Please complete the reCAPTCHA");
                    return CurrentUmbracoPage();
                }
                else
                {
                    RecaptchaVerificationResult recaptchaResult = recaptchaHelper.VerifyRecaptchaResponse();
                    if (recaptchaResult != RecaptchaVerificationResult.Success)
                    {
                        ModelState.AddModelError("reCAPTCHA", "The reCAPTCHA is incorrect");
                        return CurrentUmbracoPage();
                    }
                }
    
                bool success = false;
    
                if (ModelState.IsValid)
                {
                    success = _smtpService.SendEmail(model);
    
                }
    
                var contactPage = UmbracoContext.Content.GetById(false, model.ContactFormId);
                var successMessage = contactPage.Value<IHtmlString>("successMessage");
                var errorMessage = contactPage.Value<IHtmlString>("errorMessage");
    
                return PartialView("~/Views/Partials/Contact/result.cshtml", success ? successMessage : errorMessage);
    
            }
        }
    }
    

    and my View Model:

            public class ContactViewModel
            {
                [Required(ErrorMessage = "Please enter your name")]
                public string Name { get; set; }
    
                [Required(ErrorMessage = "please enter your email address")]
                [EmailAddress(ErrorMessage = "you must enter a valid email address")]
                public string Email { get; set; }
    
                [Required(ErrorMessage = "please enter your message")]
                [MaxLength(length: 500, ErrorMessage = "Your message must be no longer than 500 characters")]
                public string Message { get; set; }
    
                @*[Required(ErrorMessage = "please confirm you are human")]
                public string ErrorMessageCaptcha { get; set; }*@
    
                public int ContactFormId { get; set; }
            }
    

    and my Partial View

    @using (Ajax.BeginForm("SubmitForm", "ContactSurface", new AjaxOptions() { UpdateTargetId = "form-result", HttpMethod = "POST", InsertionMode = InsertionMode.Replace, OnSuccess = "contactForm.showResult", OnFailure = "contactForm.showResult" }, new { id = "contact-form" })) { @Html.HiddenFor(m => m.ContactFormId) @*@Html.AntiForgeryToken()*@
    @Html.TextBoxFor(m => m.Name, new { @class = "form-control", placeholder = "Your firstname" }) @Html.ValidationMessageFor(m => m.Name)
    @Html.TextBoxFor(m => m.Email, new { @class = "form-control", placeholder = "Your email address" }) @Html.ValidationMessageFor(m => m.Email)
    @Html.TextAreaFor(m => m.Message, new { @class = "form-control", placeholder = "Write us something", cols = "30", rows = "6" }) @Html.ValidationMessageFor(m => m.Message)
    @Html.Recaptcha(theme: Recaptcha.Web.RecaptchaTheme.Clean) @*@Html.ValidationMessageFor(m => m.ErrorMessageCaptcha)*@
    @*
    *@
    }
Please Sign in or register to post replies

Write your reply to:

Draft