c# - 无法通过 .net mvc 上的模态对话框在网站发布电子邮件发送请求上显示成功警报消息
问题描述
我的网站上有一个弹出模式对话框,用于向管理员电子邮件发送预约请求。我能够发送请求,但无法在请求完成后向用户显示成功/失败警报消息。我在 Visual Studio 2017 上使用 asp .net mvc
模态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">×</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);
}
解决方案
您正在使用JsonRequestBehavior.AllowGet
没有任何 HTTP 方法属性的控制器操作(请记住默认 HTTP 方法是GET
未指定时),但您的 AJAX 请求具有type: "POST"
选项,该选项永远不会到达控制器操作,因为它具有不同的 HTTP 方法。
您需要将 AJAX 请求更改为 use ,或者用属性(和 remove )type: "GET"
装饰控制器:[HttpPost]
JsonRequestBehavior.AllowGet
获取版本
$.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..");
}
});
发布版本
[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);
如果你想 fetch emailSent
,只需使用result.emailSent
:
if (typeof result !== "undefined" && result != null) {
$("#modalAppointment").modal('hide');
alert(result.emailSent);
}
推荐阅读
- php - 如何让用户使用 php 删除配置文件?
- file - 如何添加两个文件?
- xamarin - Xamarin 表单中 GoogleClientManager 注销的 Java 语言非法状态异常
- javascript - 如何解决 stackNavigator 的问题
- elasticsearch - Elasticsearch 通配符查询
- android - 使用 NestedScrollView 滚动 AndroidX RecyclerView 视图的行为
- android - webview不缓存
- mongodb - 根据MongoDB中两个日期的差异统计记录
- java - Java Axon 从 2.4.2 版本迁移到 4.0.3
- javascript - 从 git 子模块导入 Typescript 文件并使用 create-react-app 进行转换