0

First, I'm a student, though this is not for school. I'm trying to create a contact us page for my church's website (http://fpcoakwood.azurewebsites.net). I haven't published the contact page yet, as I'm trying to build it. I'm using Bootstrap/jQuery/ASP.NET to build the site. There is a videos page that uses ASP to get the list of videos from YouTube for our channel, and then populates the select html element from that, and I have it working so that selecting a different video loads that video into the player without a postback (though I do wish I could make the back button take me back to the prior page, rather than cycling through prior videos first).

On this page, my challenge is that I'm trying to send an email. I have the code behind working so that I can send the email, but I'm also trying to disable the send button and fadeIn a result div, which would show either success or failure to send the email. The problem is that because the postback occurs, the page reloads, and I lose the disabling of the button and the showing of the status. Here's some of the code I have so far:

HTML:

<div class="form-group">
<asp:Button class="btn btn-success" ID="sendMail" OnClick="sendMail_Click" OnClientClick="sendMail(); return false;" runat="server" UseSubmitBehavior="false" Text="Send Message" />
</div>

<div id="sendSuccess" runat="server">Success!</div>
<div id="sendFailed" runat="server">Unable to send message. Please try again later.</div>

JS:

$("#sendMail").click(function (event) {
        event.preventDefault();
        $("#sendSuccess").fadeOut();
        $("#sendFailed").fadeOut();
        $("#sendMail").attr("disabled", true);
        $("#sendMail").attr("text", "Sending...");
        return true;
    });

C#:

protected void sendMail_Click(object sender, EventArgs e)
        {
            //sendMail.Enabled = false;
            //sendMail.Text = "Sending...";
            SendMessage();
        }

If I get rid of the javascript function, I can send the email. It goes through no problems. But with the javascript function, the breakpoint in the C# function is never hit, so it's not hitting the server. What I want is to be able to validate in js before sending to the server, then send to the server without a postback, and have the server send a message to the js allowing either the fail or the success message div to fadeIn().

Any help will be VERY much appreciated. Thanks in advance!

Rich Hopkins
  • 1,861
  • 15
  • 29
  • The breakpoint is never hit because you js is canceling the event. so the form is never sent. What you are serching for is called [AJAX](http://www.w3schools.com/ajax/) – litelite Aug 19 '15 at 20:06
  • @litelite: Actually they have another mistake (`preventDefault` is not even *called*) so that is not the problem (yet) :) – iCollect.it Ltd Aug 19 '15 at 20:32
  • It is best to never mix inline event handlers with jQuery event handlers. They do not play nice together. Use jQuery event handlers for both tasks and the problem will become obvious to you :) – iCollect.it Ltd Aug 19 '15 at 20:36
  • Ok. How? I realize that I'm looking for Ajax, but doing a search turns up mostly things from 6-8 years ago, and I'm rather cautious about trying to use code so old since I know that much has changed. Can anyone point me to an example that does what I'm trying to do? Send data to code behind without postback, and also call jQuery function. Both work on their own (with postback), but I can't get them to work together, and without postback. – Rich Hopkins Aug 19 '15 at 21:14
  • Oh - and then I need to return a pass/fail from the server to the web page. Ugh. – Rich Hopkins Aug 19 '15 at 21:33
  • Edited to put in the () after preventDefault. Thanks for pointing that error out. – Rich Hopkins Aug 19 '15 at 21:54

2 Answers2

0

The jquery function runs before the C# code behind and interfere with it's result. To do what you want you could do all the work on the server-side. You can use ajax to do that. Use an updatepanel around the controls and an updateprogress with the "sending..." message. Capture the sendmessage() result and then show the #sendsuccess or #sendFailed according to it.

  • Ok.... I'm looking up what an updatepanel is now. But in the meantime, how would I get the jQuery effects like fadeIn and fadeOut? (This is my first go at a website). And I can't get divs inside an updatepanel. :/ I'm looking at all this and wondering why anyone would use ASP? I did an example of this in class with php and it was so much easier. But I want to learn ASP, too, which is why I'm doing this. – Rich Hopkins Aug 19 '15 at 21:53
  • You can add client-side script from the server-side like this: Page.ClientScript.RegisterStartupScript(Me.GetType(), "FadeInDiv", "$("#sendSuccess").fadein();", True) – Felipe C Vieira Aug 19 '15 at 22:36
  • To get anythig inside the updatepanel don't miss the ContentTemplate tag:
    – Felipe C Vieira Aug 19 '15 at 22:44
0

I ended up using the answer in this post (How to call code behind method from a javascript function?) to do what I wanted to do. Surely it could have been done with Filipe's answer, but at this point, I'm already drinking from a fire hose trying to learn what I can learn, so this was easier for me, since I already have a fair understanding of all of the pieces involved.

Here's my HTML:

<form runat="server">

                <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>

                    <div class="col-md-8 col-md-offset-2" runat="server">
                        <div class="form-group">
                            <label for="userName">Your name (requrired):</label>
                            <input type="text" class="form-control" id="userName" runat="server" />
                        </div>

                        <div class="form-group">
                            <label for="email">Email address (required):</label>
                            <input type="email" class="form-control" id="email" runat="server" />
                        </div>

                        <div class="form-group">
                            <label for="message">Message:</label>
                            <textarea class="form-control" id="message" rows="5" runat="server"></textarea>
                        </div>

                        <div class="form-group">

                            <asp:Button class="btn btn-success" ID="sendMail" runat="server" OnClientClick="sendMail(); return false;" UseSubmitBehavior="false" Text="Send Message" />
                        </div>

                    <div id="sendSuccess" runat="server">Your message has been sent. Thank you for contacting First Pentecostal Church of Oakwood. You are important to us!</div>
                    <div id="sendFailed" runat="server">Unable to send message. Please try again later. You are important to us!</div>

                    </div>

                </form>

There is an error in the HTML, as the OnClientClick doesn't find the function, but without it and the return false, the page does a postback. I'm not sure how to fix it, as the preventDefault() in the JS doesn't solve it, and using the UseSubmitBehavior by itself doesn't do it, either. But this works, though it shows as an error in the developer tools in the browser.

Here's the CSS:

#sendSuccess,
#sendFailed {
    display:none;
    border: 1px solid black;
    border-radius: 5px;
    padding: 5px;
}

#sendSuccess {
    background-color: rgba(147, 197, 75, .7);
}

#sendFailed {
    background-color: rgba(201, 48, 44, .7);
}

Here's the JavaScript:

    //Set up event handler for send message contact page button
    $("#sendMail").click(function (event) {
        event.preventDefault();
        sendMail();
    });
//above is in the $(document).ready function


function sendMail() {
    $("#sendSuccess").fadeOut();
    $("#sendFailed").fadeOut();
    $("#sendMail").prop("value", "Sending...");
    $("#sendMail").attr("disabled", true);

    var name = $("#userName").val();
    var email = $("#email").val();
    var msg = $("#message").val();

    PageMethods.SendMessage(name, email, msg, onSuccess, onError);

}

function onSuccess(result) {
    if (result) {
        $("#sendSuccess").fadeIn();
        $("#userName").prop("value", "");
        $("#email").prop("value", "");
        $("#message").prop("value", "");
        $("#sendMail").prop("value", "Send Message");
        $("#sendMail").attr("disabled", false);
    }
    else { onError(result); }
}

function onError(result) {
    $("#sendFailed").fadeIn();
    $("#sendMail").prop("value", "Try Again");
    $("#sendMail").attr("disabled", false);
}

And here's the C#:

[System.Web.Services.WebMethod()]
public static bool SendMessage(string user, string email, string msg)
{
    string to = "xxxxxxxxx@outlook.com";
    string from = "xxxxxxxxxx@outlook.com";
    string subject = "Message from OakwoodFPC.org Contact Page";
    string body = "From: " + user + "\n";
    body += "Email: " + email + "\n";
    body += msg;

    MailMessage o = new MailMessage(from, to, subject, body);
    NetworkCredential cred = new NetworkCredential("xxxxxxxxxx@outlook.com", "password");
    SmtpClient smtp = new SmtpClient("smtp.live.com", 587);
    smtp.EnableSsl = true;
    smtp.Credentials = cred;

    try
    {
        smtp.Send(o);
        return true;
    }
    catch (Exception)
    {
        return false;
    }           
}       
Community
  • 1
  • 1
Rich Hopkins
  • 1,861
  • 15
  • 29
  • Oh - the only thing I have yet to add is the validation to be sure the fields aren't empty. The email field is already automatically checked for valid email address if there is something there, but it doesn't seem to care if it is empty. I'll add that validation tomorrow. Thanks for the suggestions! – Rich Hopkins Aug 20 '15 at 04:58
  • One more thing - the onSuccess and onError don't seem to work as intended, so that is why I check the value of result in the onSuccess function before doing any of the "success" tasks. – Rich Hopkins Aug 20 '15 at 05:02