Вы используете 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);
}