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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

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?
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: stackoverflow.com/a/8968207/29407
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.
I am afraid there isn't. The dirt fix would be to use a string property instead.
I would like to point out that the contentType: 'application/json' is important. I missed this first time through.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.