I still do not own WebAPI services. I am succeeding in simple elements, but now my needs are becoming more complicated, and everything always fails.
I use MVC 5 for WebAPI and call using regular jQuery functions.
My model
Here I manage the appointment of patients in the clinic. I use the following model for patient objects and appointments:
public class Patient
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Appointment
{
public int Id { get; set; }
public DateTime Date { get; set; }
public int Order { get; set; }
public string PatientName { get; set; }
public Patient Patient { get; set; }
public int PatientId { get; set; }
public Organization Organization { get; set; }
public int OrganizationId { get; set; }
}
My DTO
public class AppointmentDto
{
public int Id { get; set; }
public int Order { get; set; }
public string PatientName { get; set; }
public PatientDto Patient { get; set; }
}
public class PatientDto
{
public string Name { get; set; }
}
First case
I want to establish a new order for meetings throughout the day. I am sending a list of JSON objects with the identifiers of the assignments to be changed and their corresponding orders.
Service Action:
[HttpPost]
public IHttpActionResult UpdateOrder(List<AppointmentDto> dto)
{
_unitOfWork.Appointments.UpdateOrder(dto);
_unitOfWork.Complete();
return Ok();
}
Service Call:
var rearrangeAppointments = function (event, ui) {
var orderedAppointments = [];
var i = 0;
$("#sortable").children().each(function () {
i++;
orderedAppointments.push({ "Id": this.getAttribute("data-id").toString(), "Order": i.toString() });
});
appointmentsService.updateOrder(orderedAppointments, done, fail);
};
var updateOrder = function (orderedAppointmens, done, fail) {
$.ajax({
url: "/api/appointments",
method: "POST",
data: orderedAppointmens,
dataType: "Json"
})
.done(done)
.fail(fail);
};
, . JavaScript, JSON . MVC Postman, . .
. , , .
:
public IEnumerable<AppointmentDto> GetAppointments(DateTime date)
{
var organizationId = _unitOfWork.ApplicationUsers.GetOrganizationId(User.Identity.GetUserId());
var appointments = _unitOfWork.Appointments.GetAppointments(date, organizationId);
return appointments.Select(Mapper.Map<Appointment, AppointmentDto>);
}
:
$("#datepicker").datepicker({
onSelect: function (dateText, inst) {
var selectedDate = $(this).datepicker('getDate');
var date = JSON.stringify(selectedDate);
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: "json",
url: "/api/appointments",
data: date,
success: function (appointments) {
alert("Service call succeeded!")
alert(appointments.length);
}
})
.fail(function () {
alert("Failure!");
});
}
});
(hardcoding date ), . ( AJAX), .
, :
datetime javascript # (Controller)
Ajax Call MVC
, .
, .
?