Use contact form inside a post

Topics: Controls
Jun 2, 2011 at 5:50 PM

Hi, I would like to be able to use the standard contact form inside a blog posting.

I'm using BlogEngine as a CMS system, and we are going to use posts for things like press releases, job opportunities, and marketing responses.

I'd like to be able to use a contact form in a page, or a post, and have it basically perform the same checks (fields filled out) and send it via email, just like the standard contact form.

Can anyone help with this or suggest how to accomplish it. I don't really want to use JotForms, as I'd rather keep everything on our server.

Thank you,
Tom Fox 

Jun 2, 2011 at 10:12 PM
Edited Oct 24, 2011 at 8:17 PM

Make a  user control using the contact.aspx and contact.aspx.cs  code,  modify it to your needs then

Enable it in pages or posts by doing this:

http://madskristensen.net/post/User-control-injection-in-BlogEngineNET-12.aspx

http://www.go4coding.com/post/2011/03/24/Embedding-user-control-inside-blog-posts-and-pages-in-blogengine-net.aspx

 

Info on how to create user controls:

http://oreilly.com/catalog/progaspdotnet/chapter/ch14.html

http://www.beansoftware.com/ASP.NET-Tutorials/User-Control.aspx



Java Blog

Jun 4, 2011 at 11:55 PM

I am getting this error with the user control for contact:

Sorry, but the following occurred while attemping to send your message: The target '__Page' for the callback could not be found or did not implement ICallbackEventHandler

Jun 4, 2011 at 11:56 PM
Edited Jun 9, 2011 at 4:01 PM

 

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="MailingList.ascx.cs" Inherits="UserControls.MailingList" %>
<%@ Import Namespace="BlogEngine.Core" %>


<div id="contact">
    <div id="divForm" runat="server">
      <h1><%=Resources.labels.contact %></h1>
      
      <div><%=BlogSettings.Instance.ContactFormMessage %></div>
      
      <label for="<%=txtName.ClientID %>"><%=Resources.labels.name %></label>
      <asp:TextBox runat="server" id="txtName" cssclass="field" />
      <asp:requiredfieldvalidator runat="server" controltovalidate="txtName" ErrorMessage="<%$Resources:labels, required %>"
 validationgroup="contact" /><br /> <label for="<%=txtEmail.ClientID %>"><%=Resources.labels.email %></label> <asp:TextBox runat="server" id="txtEmail" cssclass="field" /> <asp:RegularExpressionValidator runat="server" ControlToValidate="txtEmail" display="dynamic"
ErrorMessage
="<%$Resources:labels, enterValidEmail %>"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" validationgroup="contact" /> <asp:requiredfieldvalidator runat="server"
controltovalidate="txtEmail" ErrorMessage="<%$Resources:labels, required %>" validationgroup="contact" /><br /> <label for="<%=txtSubject.ClientID %>"><%=Resources.labels.subject %></label> <asp:TextBox runat="server" id="txtSubject" cssclass="field" /> <asp:requiredfieldvalidator runat="server"
controltovalidate
="txtSubject" ErrorMessage="<%$Resources:labels, required %>" validationgroup="contact" /><br /> <label for="<%=txtMessage.ClientID %>"><%=Resources.labels.message %></label> <asp:TextBox runat="server" id="txtMessage" textmode="multiline" rows="5" columns="30" /> <asp:requiredfieldvalidator runat="server" controltovalidate="txtMessage"
ErrorMessage
="<%$Resources:labels, required %>" display="dynamic" validationgroup="contact" /> <asp:placeholder runat="server" id="phAttachment"> <label for="<%=txtAttachment.ClientID %>"><%=Resources.labels.attachFile %></label> <asp:FileUpload runat="server" id="txtAttachment" /> </asp:placeholder> <br /><br /> <blog:RecaptchaControl runat="server" ID="recaptcha" /> <asp:HiddenField runat="server" ID="hfCaptcha" /> <asp:button runat="server" id="btnSend" Text="Send" OnClientClick="return beginSendMessage();" validationgroup="contact" /> <asp:label runat="server" id="lblStatus"
visible="false">This form does not work at the moment. Sorry for the inconvenience.</asp:label> </div> <div id="thanks"> <div id="divThank" runat="Server" visible="False"> <%=BlogSettings.Instance.ContactThankMessage %> </div> </div> </div> <script type="text/javascript"> function beginSendMessage() { if (BlogEngine.$('<%=txtAttachment.ClientID %>') && BlogEngine.$('<%=txtAttachment.ClientID %>').value.length > 0) return true; if(!Page_ClientValidate('contact')) return false; var recaptchaResponseField = document.getElementById('recaptcha_response_field'); var recaptchaResponse = recaptchaResponseField ? recaptchaResponseField.value : ""; var recaptchaChallengeField = document.getElementById('recaptcha_challenge_field'); var recaptchaChallenge = recaptchaChallengeField ? recaptchaChallengeField.value : ""; var name = BlogEngine.$('<%=txtName.ClientID %>').value; var email = BlogEngine.$('<%=txtEmail.ClientID %>').value; var subject = BlogEngine.$('<%=txtSubject.ClientID %>').value; var message = BlogEngine.$('<%=txtMessage.ClientID %>').value; var sep = '-||-'; var arg = name + sep + email + sep + subject + sep + message + sep + recaptchaResponse + sep + recaptchaChallenge; WebForm_DoCallback('__Page', arg, endSendMessage, 'contact', onSendError, false) BlogEngine.$('<%=btnSend.ClientID %>').disabled = true; return false; } function endSendMessage(arg, context) { if (arg == "RecaptchaIncorrect") { displayIncorrectCaptchaMessage(); BlogEngine.$('<%=btnSend.ClientID %>').disabled = false; if (document.getElementById('recaptcha_response_field')) { Recaptcha.reload(); } } else { if (document.getElementById("spnCaptchaIncorrect")) document.getElementById("spnCaptchaIncorrect").style.display = "none"; BlogEngine.$('<%=btnSend.ClientID %>').disabled = false; var form = BlogEngine.$('<%=divForm.ClientID %>') var thanks = BlogEngine.$('thanks'); form.style.display = 'none'; thanks.innerHTML = arg; } } function displayIncorrectCaptchaMessage() { if (document.getElementById("spnCaptchaIncorrect")) document.getElementById("spnCaptchaIncorrect").style.display = ""; } function onSendError(err, context) { if (document.getElementById('recaptcha_response_field')) { Recaptcha.reload(); } BlogEngine.$('<%=btnSend.ClientID %>').disabled = false; alert("Sorry, but the following occurred while attemping to send your message: " + err); } </script>
Jun 4, 2011 at 11:57 PM

#region Using

namespace UserControls
{
    using System;
    using System.Collections.Generic;
    using System.Collections.Specialized;
    using System.Data;
    using System.Globalization;
    using System.IO;
    using System.Linq;
    using System.Security.Cryptography;
    using System.Text;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    using BlogEngine.Core;
    using BlogEngine.Core.Web.Controls;
    using BlogEngine.Core.Web.Extensions;

    using System.Collections;
    using System.Web.UI.HtmlControls;
    using System.Net.Mail;
    using System.Text.RegularExpressions;

#endregion

    public partial class MailingList : UserControl, ICallbackEventHandler
    {

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            this.Page.ClientScript.GetCallbackEventReference(this, "arg", "callback", "context");
            btnSend.Click += new EventHandler(btnSend_Click);
            if (!Page.IsPostBack)
            {
                txtSubject.Text = Request.QueryString["subject"];
                txtName.Text = Request.QueryString["name"];
                txtEmail.Text = Request.QueryString["email"];

                GetCookie();
                phAttachment.Visible = BlogSettings.Instance.EnableContactAttachments;
                SetFocus();
            }

            if (!IsPostBack && !this.Page.IsCallback)
            {
                recaptcha.Visible = UseCaptcha;
                recaptcha.UserUniqueIdentifier = hfCaptcha.Value = Guid.NewGuid().ToString();
            }

            Page.Title = Server.HtmlEncode(Resources.labels.contact);
            
        }

        /// <summary>
        /// Sets the focus on the first empty textbox.
        /// </summary>
        private void SetFocus()
        {
            if (string.IsNullOrEmpty(Request.QueryString["name"]) && txtName.Text == string.Empty)
            {
                txtName.Focus();
            }
            else if (string.IsNullOrEmpty(Request.QueryString["email"]) && txtEmail.Text == string.Empty)
            {
                txtEmail.Focus();
            }
            else if (string.IsNullOrEmpty(Request.QueryString["subject"]))
            {
                txtSubject.Focus();
            }
            else
            {
                txtMessage.Focus();
            }
        }

        /// <summary>
        /// Handles the Click event of the btnSend control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void btnSend_Click(object sender, EventArgs e)
        {
            if (Page.IsValid && txtAttachment.HasFile)
            {
                if (!UseCaptcha || IsCaptchaValid)
                {
                    bool success = SendEmail(txtEmail.Text, txtName.Text, txtSubject.Text, txtMessage.Text);
                    divForm.Visible = !success;
                    lblStatus.Visible = !success;
                    divThank.Visible = success;
                    SetCookie();
                }
                else
                {
                    this.Page.ClientScript.RegisterStartupScript(this.GetType(), "captcha-incorrect", " displayIncorrectCaptchaMessage(); ", true);
                }
            }
        }

        private bool SendEmail(string email, string name, string subject, string message)
        {
            try
            {
                using (MailMessage mail = new MailMessage())
                {
                    mail.From = new MailAddress(BlogSettings.Instance.Email, name);
                    mail.ReplyTo = new MailAddress(email, name);

                    mail.To.Add(BlogSettings.Instance.Email);
                    mail.Subject = BlogSettings.Instance.EmailSubjectPrefix + " e-mail - " + subject;

                    mail.Body = "<div style=\"font: 11px verdana, arial\">";
                    mail.Body += Server.HtmlEncode(message).Replace("\n", "<br />") + "<br /><br />";
                    mail.Body += "<hr /><br />";
                    mail.Body += "<h3>Author information</h3>";
                    mail.Body += "<div style=\"font-size:10px;line-height:16px\">";
                    mail.Body += "<strong>Name:</strong> " + Server.HtmlEncode(name) + "<br />";
                    mail.Body += "<strong>E-mail:</strong> " + Server.HtmlEncode(email) + "<br />";

                    if (ViewState["url"] != null)
                        mail.Body += string.Format("<strong>Website:</strong> <a href=\"{0}\">{0}</a><br />", ViewState["url"]);

                    if (ViewState["country"] != null)
                        mail.Body += "<strong>Country code:</strong> " + ((string)ViewState["country"]).ToUpperInvariant() + "<br />";

                    if (HttpContext.Current != null)
                    {
                        mail.Body += "<strong>IP address:</strong> " + HttpContext.Current.Request.UserHostAddress + "<br />";
                        mail.Body += "<strong>User-agent:</strong> " + HttpContext.Current.Request.UserAgent;
                    }

                    if (txtAttachment.HasFile)
                    {
                        Attachment attachment = new Attachment(txtAttachment.PostedFile.InputStream, txtAttachment.FileName);
                        mail.Attachments.Add(attachment);
                    }

                    Utils.SendMailMessage(mail);
                }

                return true;
            }
            catch (Exception ex)
            {
                if (Security.IsAuthorizedTo(Rights.ViewDetailedErrorMessages))
                {
                    if (ex.InnerException != null)
                    {
                        lblStatus.Text = ex.InnerException.Message;
                    }
                    else
                    {
                        lblStatus.Text = ex.Message;
                    }
                }

                return false;
            }
        }

        // comment test

        #region Cookies

        /// <summary>
        /// Gets the cookie with visitor information if any is set.
        /// Then fills the contact information fields in the form.
        /// </summary>
        private void GetCookie()
        {
            HttpCookie cookie = Request.Cookies["comment"];
            if (cookie != null)
            {
                txtName.Text = Server.UrlDecode(cookie.Values["name"]);
                txtEmail.Text = cookie.Values["email"];
                ViewState["url"] = cookie.Values["url"];
                ViewState["country"] = cookie.Values["country"];
            }
        }

        /// <summary>
        /// Sets a cookie with the entered visitor information
        /// so it can be prefilled on next visit.
        /// </summary>
        private void SetCookie()
        {
            HttpCookie cookie = new HttpCookie("comment");
            cookie.Expires = DateTime.Now.AddMonths(24);
            cookie.Values.Add("name", Server.UrlEncode(txtName.Text));
            cookie.Values.Add("email", txtEmail.Text);
            cookie.Values.Add("url", string.Empty);
            cookie.Values.Add("country", string.Empty);
            Response.Cookies.Add(cookie);
        }

        #endregion

        #region CAPTCHA

        /// <summary> 
        /// Gets whether or not the user is human 
        /// </summary> 
        private bool IsCaptchaValid
        {
            get
            {
                recaptcha.Validate();
                return recaptcha.IsValid;
            }
        }

        private bool UseCaptcha
        {
            get
            {
                return
                    BlogSettings.Instance.EnableRecaptchaOnContactForm &&
                    recaptcha.RecaptchaEnabled &&
                    recaptcha.RecaptchaNecessary;
            }
        }

        #endregion


        #region ICallbackEventHandler Members

        private string _Callback;

        public string GetCallbackResult()
        {
            return _Callback;
        }

        public void RaiseCallbackEvent(string eventArgument)
        {
            string[] arg = eventArgument.Split(new string[] { "-||-" }, StringSplitOptions.None);
            if (arg.Length == 6)
            {
                string name = arg[0];
                string email = arg[1];
                string subject = arg[2];
                string message = arg[3];

                string recaptchaResponse = arg[4];
                string recaptchaChallenge = arg[5];

                recaptcha.UserUniqueIdentifier = hfCaptcha.Value;
                if (UseCaptcha)
                {
                    if (!recaptcha.ValidateAsync(recaptchaResponse, recaptchaChallenge))
                    {
                        _Callback = "RecaptchaIncorrect";
                        return;
                    }
                }

                if (SendEmail(email, name, subject, message))
                {
                    _Callback = BlogSettings.Instance.ContactThankMessage;
                }
                else
                {
                    _Callback = "This form does not work at the moment. Sorry for the inconvenience.";
                }
            }
            else
            {
                _Callback = "This form does not work at the moment. Sorry for the inconvenience.";
            }
        }

        #endregion



    }
}
	

Jun 4, 2011 at 11:59 PM

Any help would be great thanks!!!

Jun 7, 2011 at 1:20 PM

bump :)

Jun 7, 2011 at 6:33 PM

bump :)

Jun 9, 2011 at 7:08 AM

bump :)

Jun 9, 2011 at 7:14 AM

Is your problem still un-resolved ?

Basically do you want to use the contact kind of functionality in side posts, right ?

Jun 9, 2011 at 4:00 PM

Problem is still un-resolved.

 

I want a Contact User Control that can be injected into a post or a page.

 

Like this:  http://www.go4coding.com/post/2011/03/24/Embedding-user-control-inside-blog-posts-and-pages-in-blogengine-net.aspx

 

The code above works but getting this error when trying to submit:

 

Sorry, but the following occurred while attemping to send your message:

The target '__Page' for the callback could not be found or did not

implement ICallbackEventHandler

 

End goal is to have zero "Stand" alone pages in BE.   Would like to have all pages editable through the ADMIN section and with in the BE app_pool.

 

The Contact control is the first step.

 

Also thomasfox requested this originally:

 

"I'd like to be able to use a contact form in a page, or a post, and have it basically

perform the same checks (fields filled out) and send it via email, just like the standard contact form."

Jun 9, 2011 at 4:15 PM

Okay, i made some changes and I have created one contact user control and embedded it with post page. I have uploaded the zip file on my blog.

Follow this link to use contact form on post page and download the files. - http://www.blogenginewall.com/post/2011/06/09/How-To-Use-Contact-Form-Inside-BlogEngineNet-Post.aspx

Regards,

http://www.blogenginewall.com

Jun 9, 2011 at 4:42 PM

Is there a way to make this a user control?

That can be injected in to a Page or Post on a per page/post base?:   [usercontrol: ~/UserControls/contact.ascx]

 

Not every page or post needs the contact form just curtain pages.

 

Like: press releases, job opportunities, and marketing responses.

 

Thanks

Jun 13, 2011 at 1:53 AM

bump

Jun 13, 2011 at 9:43 PM

bump

Jun 21, 2011 at 9:12 PM

bump

Jul 5, 2014 at 3:04 PM
Hi,
Has anyone got a solution to this by any chance?

I've tried to replace the form action of the page in a user control with:

Parent.Page.Form.Action = FORMURL;

But it gets overwritten later on in the execution so the current page url is set as the form action.

Is there a way I can override things so my own action gets to be replaced into the page's form action?

Hope someone can help

Thanks

Sid