Lamloumi Afif
Lamloumi Afif

Reputation: 9081

Get null parameter in the server side after ajax call

I have a weird problem in my ASP.Net WebApi application. I have this client side code:

 var arr = [];
for (var i = 0; i < checkarray.length; i++) {
    if (checkarray[i] == 1) arr.push(ids[i]);
}
console.log(arr);
$.ajax({
    type: "post",
    async: false,
    url: "/api/Demande/ReservationAgendaByDrivers", 
    data: arr,
    success: function (data) {
        // ...
    }
});

In the server side:

[HttpPost]
public IEnumerable<ReservationModel> ReservationAgendaByDrivers(int[]  tab)
{
    List<ReservationModel> outlst = new List<ReservationModel>();
    List<ReservationModel> model = GetListReservation().ToList();
    foreach (ReservationModel item in model)
    {
        if (!item.id_chauffeur.HasValue) 
            continue;

        if (tab.Contains(item.id_chauffeur.Value)) 
            outlst.Add(item);
    }
    return outlst.OrderByDescending(x => x.id_demande);
}

I get for example, as output in the browser, this array :

[7, 5, 1]

but the tab parameter in the server side is always null !!

I need to know :

  1. What are the reasons of this error?
  2. How can I fix my code?

Upvotes: 1

Views: 425

Answers (4)

Lamloumi Afif
Lamloumi Afif

Reputation: 9081

Thanks everybody,

I fix my code by editing my code like this :

$.ajax({
        type: "post",
        async:false,
        url: "/api/Demande/ReservationAgendaByDrivers",
        data: JSON.stringify(arr), 
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
        .......
                                 }
       });

Upvotes: 0

Jai
Jai

Reputation: 74738

What are the reasons of this error?

int[] tab is expecting a var in the params named tab which is not there as you are trying to send an array arr.

How can I fix my code?

Send an object in the data :

data: { tab: arr }, // here tab is the key which belongs to int[] tab at backend

and async:false is not a good choice to set it to false. This shouldn't be used to set it to false as there are ways to do the things correctly with promises.

Upvotes: 2

Kaushik Maheta
Kaushik Maheta

Reputation: 1901

console.log(arr);
$.ajax({
    type: "post",
    url: "/api/Demande/ReservationAgendaByDrivers", 
    data:{tab:arr},
    success: function (data) {
   .............
                             }});

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337701

For the ModelBinder to work correctly you need to provide the array in an object under the tab property. You should also remove the async: false as it is unspeakably bad practice to use it.

$.ajax({
    type: "post",
    url: "/api/Demande/ReservationAgendaByDrivers", 
    data: {
        tab: arr
    },
    success: function (data) {
        // handle the response here...
    }
});

Upvotes: 2

Related Questions