【发布时间】:2018-09-20 22:50:45
【问题描述】:
我一直在尝试从 jquery json 调用控制器中的 .cs 方法,它被调用但传递的参数始终为空。为什么?即使我检查了控制台日志,它也显示了正在传递的值,但不知何故它没有传递给方法。它是空的。
$('#AppointmentDate').change(function () {
var AppointmentDate = '2018-04-30'; //document.getElementById('AppointmentDate').value;
$.ajax
({
url: '@Url.Action("GetTimeSlotsByDate", "Appointment")',
type: 'GET',
contentType: "application/json; charset= utf-8",
data: JSON.stringify(AppointmentDate),
dataType: 'json',
success: function (results) {
$("#fk_TimeSlotID").html(""); // clear before appending new list
$.each(results, function (i, slot) {
$("#fk_TimeSlotID").append(
$('<option></option>').val(slot.TimeSlotID).html(slot.FromTo));
});
console.log('Time slots returned');
console.log(AppointmentDate);
}
});
方法:
public ActionResult GetTimeSlotsByDate(DateTime? RequestedAppointmentDate)
{
TimeSlotsRepository TimeSlotsRep = new TimeSlotsRepository();
List<TimeSlotsModel> ListTimeSlotsModel = TimeSlotsRepository.getTimeSlotsByDate(RequestedAppointmentDate);
return Json(ListTimeSlotsModel, JsonRequestBehavior.AllowGet);
}
这是呈现的网址
http://localhost:13924/Appointment/GetTimeSlotsByDate?"2018-04-30"
【问题讨论】:
-
data: { RequestedAppointmentDate: AppointmentDate }并删除无意义的contentType: "application/json; charset= utf-8",(GET 没有正文) -
@StephenMuecke:我做到了,但它仍然不起作用。同样的问题
-
它确实有效(它会生成带有
..../GetTimeSlotsByDate?RequestedAppointmentDate=2018-04-30的正确网址 -
如果您使用您提供的代码(硬编码日期字符串)并且更改为
data: { RequestedAppointmentDate ...,那么它应该可以工作。如果您使用的是$("AppointmentDate").val(),那么很可能 that val 的格式不正确,因此它不会被识别为日期(例如可能是dd/mm/yyyy)格式,而 .Net 会期待mm-dd-yyyy格式)。 -
@IanKemp,OP 正在以 iso 格式发送日期,因此它始终会正确绑定
标签: c# jquery asp.net json asp.net-mvc