简体   繁体   中英

Getting date value null in ajax request

I am using Ajax request to send the value of date to my API Controller here is my ajax call

 $("#txtpdate").on("changeDate", function (e) {
        var Date =$('#txtpdate').val();
        console.log(Date);
        $.ajax({
            type: 'POST',
            contentType: false,
            url: '/api/ServiceProvider/GetUpdatedPrice',
            data:{date: Date  },
            cache: false
        }).done(function (response) {

        });
});

And here is my api controller

[HttpPost]
[Route("GetUpdatedPrice")]
public  ServiceProviderDocuments GetUpdatedPrice(DateTime date)
{
    return  ServiceProviderDocumentsGateway.GetUpdatedPriceofBike(date);
}

I am getting the desired value in console.log(Date) but when I reached to the controller it is showing null value please take a look on the below image 在此处输入图片说明

Just solved by doing this

  var dt=$('#txtpdate').val();
    ko.toJSON({ date: new Date(dt)})

then you will get date in action.

hi try to parse request into json and your date field into date like to: new Date

 var promise=jQuery.ajax({
        url: url,
        type: 'POST',
        data: JSON.stringify(data),
        contentType: 'application/json; charset=utf-8'
    }).promise();

You should declare the date parameter as DateTime, like:

[HttpPost]
[Route("GetUpdatedPrice/{pDate:datetime}")]
public  ServiceProviderDocuments GetUpdatedPrice(DateTime pDate)
{
    return ServiceProviderDocumentsGateway.GetUpdatedPriceofBike(pDate);

}

Do the following:

  1. Change the type of the parameter to string:

     [HttpPost] [Route("GetUpdatedPrice")] public ServiceProviderDocuments GetUpdatedPrice(string date) { //Convert date to Datetime here } 
  2. Change the contentType to:

     contentType: 'application/json; charset=utf-8', 
  3. Stringify the date :

     data: JSON.stringify({ date: Date }), 

In my case, the date was a property of a object and the "set" was only "internal", so I remove it and now it's working.

After:

public DateTime DataInicialFiltro { get; internal set; }

Before:

public DateTime DataInicialFiltro { get; set; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM