arame3333
arame3333

Reputation: 10223

How to send JSON date fields to web core API?

I have this AJAX request;

   addDataToDatabase = function (callback, errorCallback, url, data) {
        $.ajax({
            async: true,
            url: url,
            contentType: "application/json",
            dataType: "text",
            data: data,
            type: "POST"
        })
            .done(function (data) {
                callback(data);
            })
            .fail(function (data) {
                errorCallback(data);
            });

which sends data to the web core API;

data "{\"InspectionId\":\"4471\",\"DateOfVisit\":\"25/09/2017 00:00:00\",\"NoAccessId\":\"2\",\"NoAccessComment\":\"lkjh lkjhlkjhlkhjlkjhlklkjh lkh lkh kjh dsf\"}"

Which is pick up with this method

[HttpPost("addNoAccess")]
        public async Task<IActionResult> AddNoAccessVisit([FromBody] InspectionVisitNoAccessDto noAccessVisit)

The definition of the dto is

public class InspectionVisitNoAccessDto
    {
        public int InspectionId { get; set; }
        public DateTime DateOfVisit { get; set; }
        public int NoAccessId { get; set; }
        public string NoAccessComment { get; set; }

        public override string ToString()
        {
            return $"No Access Inspection Visit, date of visit {DateOfVisit.ToLongDateString()}, id = {NoAccessId}, comment = {NoAccessComment}";
        }
    }

The DateOfVisit field is a date field. With the this definition, the input string for the date field does not appear to be converted from a string to a date field, as the whole object is null. But if I change the definition from DateTime to string, everything is fine. But I would prefer to keep the definition as it is. Is there something with the JSON input I can do to fix this?

Upvotes: 0

Views: 132

Answers (1)

Lukas Kubis
Lukas Kubis

Reputation: 929

instead of sending the date in format 25/09/2017 00:00:00, try to send it in ISO8601 format.

Example:

var d = new Date();
var n = d.toISOString();

// result
2017-09-29T14:15:39.409Z

Example is taken from w3schools.com

Upvotes: 1

Related Questions