0

I'm trying to pass a list of orderlines to a async controller action using Javascript:

var model = "<some JSON string>";
$.ajax({ type: "POST",
  url: "/MyController/MyAction",
  datatype: "json",
  data: { 'orderLines': model},
  success: function(msg) {
     ...
  }
});

When I check the model variable in runtime, the values of the orderline properties are set ok. But when I put a breakpoint in my controller action, the properties of the orderline incoming parameter are 0. It looks like the JSON string wasn't properly deserialized.

The controller action looks like this:

public ActionResult AsyncUpdateOrderline(List<OrderLine> orderLines)
{
  ...
}

How can I correctly pass a complex object to a async controller action?

Thanks, Nils

tereško
  • 58,060
  • 25
  • 98
  • 150
ngruson
  • 1,176
  • 1
  • 13
  • 25

1 Answers1

6

You need to set the request Content-Type header and also use the JSON.stringify method to send data to the controller:

var model = [
    { quantity: 1, name: 'some name 1' },
    { quantity: 2, name: 'some name 2' }
];

$.ajax({ 
    url: '/MyController/MyAction',
    type: 'POST',
    contentType: 'application/json',
    data: JSON.stringify({ orderLines: model }),
    success: function(msg) {
        ...
    }
});

Notice how the model should not be a JSON string but a javascript array object where each element is reflecting the structure of your OrderLine model.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Thanks, it's almost working now. The only thing that doesn't work: I have a UnitPrice object in the order line. All fields of this object are deserialized ok, except for the Amount field. It's 0 in the controller action whereas it's set with a decimal value in the JSON string. Any ideas? – ngruson Mar 11 '13 at 11:13
  • Try setting it as string in your javascript object. For example: `{ unitPrice: '12.34' }` instead of `{ unitPrice: 12.34 }`. If you are interested in the details about why this is necessary you may take a look at the following answer where I explained this: http://stackoverflow.com/a/8968207/29407 – Darin Dimitrov Mar 11 '13 at 11:19
  • The JSON string is generated by JavaScriptSerializer().Serialize(obj). Is there any smart way of influencing how JavaScriptSerializer handles decimal values? If not, I have to make a dirtier fix. – ngruson Mar 11 '13 at 11:35
  • I am afraid there isn't. The dirt fix would be to use a string property instead. – Darin Dimitrov Mar 11 '13 at 11:37
  • I would like to point out that the contentType: 'application/json' is important. I missed this first time through. – stricq Sep 28 '13 at 17:42