3
votes

I have a contact us form in a modal dialog box using jQuery in an MVC application. The box popups up fine, but when I click on the submit button in the dialog box, its not getting to my action method. I've tried a few things, but can't figure out what's wrong. Can someone see what I might be doing wrong? Thanks.

PartialView (Contact Us form):

@model BackgroundSoundBiz.Models.EmailModel

<form id="sendEmailForm">
    <div id="sendForm">
        @Html.LabelFor(m => m.senderName)<br />
        @Html.TextBoxFor(m => m.senderName)
        <br />
        @Html.LabelFor(m => m.senderEmail)<br />
        @Html.TextBoxFor(m => m.senderEmail)
        <br />
        @Html.LabelFor(m => m.message)<br />
        @Html.TextAreaFor(m => m.message)
        <br />
        <input class="close" name="submit" type="submit" value="Submit" />
    </div>
</form>

Model:

    public class EmailModel
    {
        [Required]
        [Display(Name = "Name")]
        public string senderName { get; set; }

        [Required]
        [Display(Name = "Email")]
        public string senderEmail { get; set; }

        [Required]
        [Display(Name = "Message")]
        public string message { get; set; }
    }

jQuery:

<script type="text/javascript">
        $.ajaxSetup({ cache: false });

        $(document).ready(function () {
            $(".openDialog").on("click", function (e) {
                e.preventDefault();
                $("<div></div>").addClass("dialog")
                    .attr("id", $(this).attr("data-dialog-id"))
                    .appendTo("body")
                    .dialog({
                        title: $(this).attr("data-dialog-title"),
                        close: function () { $(this).remove() },
                        width: 500,
                        height: 350,
                        show: { effect: "blind", duration: 1000 },
                        hide: { effect: "explode", duration: 1000 },
                        modal: true
                    }).load(this.href);
            });

            $(".close").on("click", function (e) {
                e.preventDefault();

                var senderName = $("#Name").val();
                var senderEmail = $("#Email").val();
                var message = $("#Message").text();

                $.ajax({
                    type: "POST",
                    url: "/Home/SendEmail",
                    data: { "senderName": senderName, "senderEmail": senderEmail, "message": message },
                    success: function (data) {
                        alert("Your email was successfully sent.");
                        $(this).closest(".dialog").dialog("close");
                    },
                    error: function (data) {
                        alert("There was an error sending your email.  Please try again or contact system administrator.");
                        $(this).closest(".dialog").dialog("close");
                    }
                })
            });
        });
    </script>

Controller:

        public ActionResult SendEmail()
        {
            return PartialView("SendEmail", new EmailModel());
        }

        [HttpPost]
        public ActionResult SendEmail(EmailModel model)
        {
            bool isSuccessful = true;

            if (ModelState.IsValid)
            {
                //send email
            }

            return Json(isSuccessful);
        }
1

1 Answers

2
votes

You dynamically adding the form to the DOM using .load(this.href); which means you need to use event delegation to handle the button. Change

$(".close").on("click", function (e) {

to

$(document).on('click', '.close', function(e) {`

although you should replace document with the closest ancestor that exists on the page when you first render the view.

In addition, your jQuery selectors are incorrect and you will not be posting any values related to your model. The correct selectors are based on the id attributes generated by the HtmlHelper methods are

var senderName = $("#senderName").val();
var senderEmail = $("#senderEmail").val();
var message = $("#message").val();

however its better to use the .serialize() method which will correctly serialize your form controls

$.ajax({
    type: "POST",
    url: '@Url.Action("SendEmail", "Home")', // don't hard code
    data: $('#sendEmailForm').serialize(),
    success: function (data) {
        ....