I have a JavaScript variable which is basically an array of bounding boxes (called bounds). Each array element is in the form of:
{
XHigh: -71.00742992911023,
XLow: -71.00670274612378,
YHigh: 42.09467040703646,
YLow: 42.09458047487587
}
And I’m trying to send it to an action method via POST:
$.ajax({
url: '/Map/GetLocations',
type: 'POST',
data: { boxes: bounds },
success: function(data) {
// doing something with the result
}
});
On the server, I consume the data into the action method as such:
[HttpPost]
public ActionResult GetLocations(IList<BoundingBox> boxes)
{
// do something with boxes and return some json
}
With the DTO class defined as:
public class BoundingBox
{
public decimal XHigh { get; set; }
public decimal XLow { get; set; }
public decimal YHigh { get; set; }
public decimal YLow { get; set; }
}
Within the action method the boxes value does contain the correct number of elements that I sent in the POST. However, all of the decimal values are 0. I tried changing them to doubles in the DTO, still 0.0. I tried changing them to strings and they were empty.
Am I missing something in the model binding on how to populate these values? How can I send this array of objects to my action method?
I wrote a little helper for this problem because I got also stuck with some variations of your problem. I worked around these problems by sending a serialized version of my JS object to the server (using
JSON.stringify()) and let MVC deserialize it on-the-fly.The first class I wrote is the
JsonParameterAttribute. It instructs MVC to use myTypedJsonBinderwhen binding the decorated parameter.The
TypedJsonBindertakes the decorated parameter’s value as string and tries to deserialize it to the parameter’s type using the Json.NET library in my case. (You can use other deserialization technologies, of course.)You can then use the
JsonParameterAttributelike this:And don’t forget to serialize: