Passing objects from Ajax to C # WebApi

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
{
    // Personal data
    public int Id { get; set; }
    public string Name { get; set; }
}

public class Appointment
{
    public int Id { get; set; }
    public DateTime Date { get; set; }      // date only
    public int Order { get; set; }
    public string PatientName { get; set; }

    // Parent data
    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:

// Handler methods
var rearrangeAppointments = function (event, ui) {
    // Json object to pass
    var orderedAppointments = [];

    // Looping through appointments
    var i = 0;
    $("#sortable").children().each(function () {
        // Set new order
        i++;
        orderedAppointments.push({ "Id": this.getAttribute("data-id").toString(), "Order": i.toString() });
    });

    // Call service
    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({
            // TODO: Refactor to pettern
            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 , .

, . ?

+4
2

: -? , URL- ":" (12:00), HTTP-

+1

...

( )

JSON.stringify(orderedAppointmens) contentType: 'application/json; charset=utf-8' . :

var updateOrder = function (orderedAppointmens, done, fail) {
    orderedAppointmens = JSON.stringify(orderedAppointmens);

    $.ajax({
        url: "/api/appointments",
        method: "POST",
        data: orderedAppointmens,
        contentType: 'application/json; charset=utf-8',
        dataType: "Json"
    })
    .done(done)
    .fail(fail);
};

( Date)

JSON dataType URL-, :

$.ajax({
    url: "/api/appointments?date=" + selectedDate.toISOString(),
    type: "GET",
    success: function (appointments) {
        alert(appointments.length);
    }
});

, Date DateTime .

0

Source: https://habr.com/ru/post/1673191/


All Articles