javascriptc#asp.netasp.net-mvcasp.net-ajax

ASP.NET MVC after serializing my data and sending http POST request the Controller receives a null parameter


I am trying to send an array with about 600 items of type Customer. The latter is a class I am using as a model which contains:

public class Customer
{
  int ID {get; set;}
  string Name {get; set;}
  string LastName {get; set;}
}

In my JavaScript file I am sending this data via ajax as follows:

function ExecuteSendCustomerData(customers) {
            $.ajax({
                type: "POST",
                dataType: 'json',
                contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
                data: JSON.stringify(customers),
                url: "/MyHomeController/SendCustomerDataToBackend",
            });
}

then in my HomeController I have my method set up as follows:

[HttpPost]
public void SendCustomerDataToBackend(string myJsonData) // this parameter is null
{    
    var deserializedNodeData = JsonSerializer.Deserialize<IEnumerable<Customer>>(myJsonData);
    
     //...do something with this deserialized code
}

I can verify that when the ExecuteSendCustomerData(...) gets called that the customers parameter has 600 items and the data is showing up correctly when I debug it. The issue happens when I receive the data in my c# controller class. When I put my breakpoint in this function it only shows me myJsonData is null.

Can anyone tell me what I am doing wrong?


Solution

  • The idiomatic way to do this is to create a model class, as you've already done with Customer, and then declare that your action method receives a model of this type. In this case, you're expecting a collection, so try, e.g., an array:

    [HttpPost]
    public void SendCustomerDataToBackend(Customer[] customers)
    {    
         //...do something with customers
    }
    

    In other words, by default the ASP.NET framework handles the serialization and deserialization for you.

    (You can do manual deserialization if you really need it, but that's not how the framework designers expect you to use the technology.)