1
Vote

Does not return user's input values when an error occurs

description

When the user submits a message and an error occurs (like a required field is not shown) the module loses the values forcing the user to (hopefully) re-enter all the values and message.

Although the view is done with a driver=>view=>controller=>driver=>view, values can be (indirectly) returned from the controller to the the View using TempData.

In the SendContactEmail (..) I'd rework the service so it returns a success/failure of the send and rework the function like

                 bool  sentSuccessfully = _contactFormService.SendContactEmail(name, email, subject, message, contactForm.RecipientEmailAddress);
                if (!sentSuccessfully)
                {
                    TempData["name"] = name;
                    TempData["email"] = email;
                    TempData["email2"] = email2; //I'm taking the email twice to verify it, hence this
                    TempData["subject"] = subject;
                    TempData["message"] = message;

                }
then in the view its possible to test for the existence of the TempData and redisplay the values: ie.
 <input id="Name" class="text" name="Name" type="text" placeholder="@T("Your Name")" @if( TempData.ContainsKey("Name") ) {<text>value="@TempData["Name"]"</text> }/>
           

comments

jonp123 wrote May 22, 2013 at 6:15 AM

Not totally tested but should work/capture the idea of when to return the input values to the user.
       public bool SendContactEmail(string name, string email, string subject, string message, string sendTo)
        {
            var success = ValidateContactFields(name, email, message);
            if (success)
            {
                SmtpSettingsPart smtpSettings = _orchardServices.WorkContext.CurrentSite.As<SmtpSettingsPart>();
                if (smtpSettings != null && smtpSettings.IsValid())
                {
                    SmtpClient mailClient = BuildSmtpClient(smtpSettings);
                    ContactFormSettingsRecord contactFormSettings = _orchardServices.WorkContext.CurrentSite.As<ContactFormSettingsPart>().Record;

                    if (contactFormSettings.EnableSpamProtection && MessageIsSpam(email, message))
                    {
                        // This option allows spam to be sent to a separate email address.
                        if (contactFormSettings.EnableSpamEmail && !string.IsNullOrEmpty(contactFormSettings.SpamEmail))
                        {
                            try
                            {
                                MailMessage mailMessage = new MailMessage(email, contactFormSettings.SpamEmail, subject, name + " writes:\r\n\r\n" + message);
                                mailMessage.IsBodyHtml = false;
                                mailClient.Send(mailMessage);
                                string spamMessage = string.Format("Your message was flagged as spam. If you feel this was in error contact us directly at: {0}", sendTo);
                                success = false;
                                _notifier.Information(T(spamMessage));
                            }
                            catch (Exception e)
                            {
                                Logger.Error(e, "An unexpected error while sending a contact form message flagged as spam to {0} at {1}", contactFormSettings.SpamEmail, DateTime.Now.ToLongDateString());
                                string errorMessage = string.Format("Your message was flagged as spam. If you feel this was in error contact us directly at: {0}", sendTo);
                                success = false;
                                _notifier.Error(T(errorMessage));
                            }
                        }
                    }
                    else
                    {
                        try
                        {
                            MailMessage mailMessage = new MailMessage(email, sendTo, subject, name + " writes:\r\n\r\n" + message);
                            mailMessage.IsBodyHtml = false;
                            mailClient.Send(mailMessage);
                            Logger.Debug("Contact form message sent to {0} at {1}", sendTo, DateTime.Now.ToLongDateString());
                            _notifier.Information(T("Thank you for your inquiry, we will respond to you shortly."));
                        }
                        catch (Exception e)
                        {
                            Logger.Error(e, "An unexpected error while sending a contact form message to {0} at {1}", sendTo, DateTime.Now.ToLongDateString());
                            string errorMessage = string.Format("An unexpected error occured when sending your message. You may email us directly at: {0}", sendTo);
                            success = false;
                            _notifier.Error(T(errorMessage));
                        }
                    }
                }
                else
                {
                    string errorMessage = string.Format("Our email server isn't configured. You may email us directly at: {0}", sendTo);
                    success = false;
                    _notifier.Error(T(errorMessage));
                }                
            }
            return success;
        }

        #endregion

        private SmtpClient BuildSmtpClient(SmtpSettingsPart smtpSettings)
        {
            SmtpClient mailClient = new SmtpClient();
            mailClient.Host = smtpSettings.Host;
            mailClient.Port = smtpSettings.Port;
            mailClient.EnableSsl = smtpSettings.EnableSsl;
            mailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            mailClient.UseDefaultCredentials = !smtpSettings.RequireCredentials;
            if (!mailClient.UseDefaultCredentials && !String.IsNullOrWhiteSpace(smtpSettings.UserName))
            {
                mailClient.Credentials = new NetworkCredential(smtpSettings.UserName, smtpSettings.Password);
            }
            return mailClient;
        }

        private bool ValidateContactFields(string name, string email, string message)
        {
            bool isValid = true;
            const string emailAddressRegex = @"^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$";

            if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(email) || string.IsNullOrEmpty(message))
            {
                _notifier.Error(T("All contact fields are required."));
                isValid = false;
            }
            else
            {
                Match emailMatch = Regex.Match(email, emailAddressRegex);
                if (!emailMatch.Success)
                {
                    _notifier.Error(T("Invalid email address."));
                    isValid = false;
                }
            }

            return isValid;
        }