Невозможно отобразить сообщение об успехе на веб-сайте после отправки электронного письма через модальное диалоговое окно .net mvc - PullRequest
0 голосов
/ 21 декабря 2018

У меня есть всплывающее модальное диалоговое окно на моем веб-сайте, которое я использую для отправки запроса о встрече на адрес электронной почты администратора.Я могу отправить запрос, но не могу показать успешное сообщение / сообщение об ошибке пользователю после того, как запрос завершен.я использую asp .net mvc на visual studio 2017

модальный html:

<!-- Modal -->
    <div class="modal fade" id="modalAppointment" tabindex="-1" role="dialog" aria-labelledby="modalAppointmentLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="modalAppointmentLabel">Appointment</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form action="#">
                        <div class="form-group">
                            <label for="appointment_name" class="text-black">Full Name*</label>
                            <input id="getAppointmentFullName" type="text" class="form-control">
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="appointment_phone" class="text-black">Phone*</label>
                                    <input id="getAppointmentPhone" type="text" class="form-control">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="appointment_email" class="text-black">Email</label>
                                    <input id="getAppointmentEmail" type="text" class="form-control">
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="appointment_date" class="text-black">Date*</label>
                                    <input id="appointment_date" type="text" class="form-control">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="appointment_time" class="text-black">Time*</label>
                                    <input id="appointment_time" type="text" class="form-control">
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="form-group">
                                <label for="appointment_service" class="text-black">Choose the Service* (at least one)</label>
                                <div class="checkboxInline"><input id="ivf" type="checkbox" name="serviceType" value="IVF">IVF<br> </div>
                                <div class="checkboxInline"><input id="derma" type="checkbox" name="serviceType" value="Dermatolology"> Dermatolology<br></div>
                                <div class="checkboxInline"><input id="lapro" type="checkbox" name="serviceType" value="Laproscopy"> Laproscopy<br> </div>
                                <div class="checkboxInline"> <input id="opto" type="checkbox" name="serviceType" value="Optometry"> Optometry<br> </div>
                                <div class="checkboxInline">   <input id="gm" type="checkbox" name="serviceType" value="General Medicine"> General Medicine<br> </div>
                                <div class="checkboxInline">
                                    <input id="physio" type="checkbox" name="serviceType" value="Physiotherapy"> Physiotherapy<br>
                                </div>
                                <div class="checkboxInline">
                                    <input id="ortho" type="checkbox" name="serviceType" value="Orthopedic"> Orthopedic<br>
                                </div>
                                <div class="checkboxInline">
                                    <input id="pedia" type="checkbox" name="serviceType" value="Pediatric"> Pediatrics<br>
                                </div>
                                <div class="checkboxInline">
                                    <input id="gynae" type="checkbox" name="serviceType" value="Obs & Gynae"> Obs and Gynae<br>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="appointment_message" class="text-black">Message</label>
                            <textarea id="appointment_message" class="form-control" cols="30" rows="2"></textarea>
                        </div>
                        <div class="form-group">
                            <input id="getAppointmentSubmit" type="submit" value="Submit" data-loading-text="Submitting...." class="btn btn-primary">
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

метод щелчка:

<script type="text/javascript">
        $(document).ready(function () {
            $('a').click(function (e) {
                e.preventDefault();
            });
            $("#btnRequestAppointment").click(function () {
                $("#modalAppointment").modal('show');
            });
            $("#getAppointmentSubmit").click(function () {
                var name = $("#getAppointmentFullName").val();
                var contactNumber = $("#getAppointmentPhone").val();
                var email = $("#getAppointmentEmail").val();
                var date = $("#appointment_date").val();
                var time = $("#appointment_time").val();
                var comments = $("#appointment_message").val();
                var servicesNeeded = [];
                $("input:checked").each(function () {
                    servicesNeeded.push($(this).val());
                });
                if ($.trim(name).length == 0 || $.trim(contactNumber).length == 0 || $.trim(date).length == 0 ||
                    $.trim(time).length == 0 || servicesNeeded.length == 0) {
                    alert('Fields marked with * are mandatory. Please enter them all and click Submit.');
                };
                var detail = {
                    Name: name, ContactNumber: contactNumber, Email: email, ServicesNeeded: servicesNeeded, Date: date,
                    Time: time, Comments: comments
                };
                $.ajax({
                    type: 'POST',
                    url: '/Home/RequestAppointment',
                    data: JSON.stringify(detail),
                    contentType: 'application/json',
                    dataType: 'JSON',
                    cache: false,
                    success: function (result) {
                        var response = JSON.parse(result.responseText);                       
                        if (response && response.emailSent == "sent") {
                            $("#modalAppointment").modal('hide');
                            alert(response);
                        }
                    },
                    error: function (xhr) {
                        var response = JSON.parse(xhr.responseText);
                        $("#modalAppointment").modal('hide');
                        alert("Error has occurred..");  
                    }
                });
            });
        });
    </script>

действие контроллера:

public async Task<JsonResult> RequestAppointment(AppointmentDetailsModel appointmentRequest)
        {
            appointmentRequest.Validate();
            //var result = false;
            string message = $"Appointment request from: {appointmentRequest.Name}; Phone Number: {appointmentRequest.ContactNumber}. They are looking to get: " +
               $"{string.Join(",", appointmentRequest.ServicesNeeded)} services on Date: {appointmentRequest.Date} at Time {appointmentRequest.Time}. Message: {appointmentRequest.Comments}";
            var response = await SendEmail(message);
            if (response == "sent")
                return Json(new { emailSent = "sent" }, JsonRequestBehavior.AllowGet);
            else
                return Json(new { emailSent = "failed" }, JsonRequestBehavior.AllowGet);
        }

1 Ответ

0 голосов
/ 21 декабря 2018

Вы используете JsonRequestBehavior.AllowGet и действие контроллера без какого-либо атрибута метода HTTP (помните, что метод HTTP по умолчанию - GET, если он не указан), но ваш запрос AJAX имеет опцию type: "POST", которая никогда не достигает действия контроллера, поскольку оноимеет другой метод HTTP.

Вам нужно либо изменить AJAX-запрос на использование type: "GET", либо вместо этого украсить контроллер атрибутом [HttpPost] (и удалить JsonRequestBehavior.AllowGet):

GET version

$.ajax({
    type: 'GET',
    url: '/Home/RequestAppointment',
    data: JSON.stringify(detail),
    contentType: 'application/json',
    dataType: 'JSON',
    cache: false,
    success: function (result) {
        var response = JSON.parse(result.responseText);                       
            if (response && response.emailSent == "sent") {
                $("#modalAppointment").modal('hide');
                alert(response);
            }
    },
    error: function (xhr) {
            var response = JSON.parse(xhr.responseText);
            $("#modalAppointment").modal('hide');
            alert("Error has occurred..");  
    }
});

POST-версия

[HttpPost]
public async Task<JsonResult> RequestAppointment(AppointmentDetailsModel appointmentRequest)
{
    appointmentRequest.Validate();

    string message = $"Appointment request from: {appointmentRequest.Name}; Phone Number: {appointmentRequest.ContactNumber}. They are looking to get: " +
    $"{string.Join(",", appointmentRequest.ServicesNeeded)} services on Date: {appointmentRequest.Date} at Time {appointmentRequest.Time}. Message: {appointmentRequest.Comments}";
    var response = await SendEmail(message);
    if (response == "sent")
        return Json(new { emailSent = "sent" });
    else
        return Json(new { emailSent = "failed" });
}

Обновление:

По результатам успешной работы AJAX, кажетсяЭта строка ниже вызывает проблему, поскольку result.responseText может возвращать undefined, поскольку свойство может не существовать внутри result:

var response = JSON.parse(result.responseText);

Если вы хотите получить emailSent, просто используйте result.emailSent вместо:

if (typeof result !== "undefined" && result != null) {
    $("#modalAppointment").modal('hide');
    alert(result.emailSent);
}
...