I read that "javascript is JSON" in other SO posts. I am having difficulty translating this theory to my application. I perform a POST with jQuery
$.ajax({
type: 'POST',
url: 'Pricing/Create',
data: items,
success: function () { alert('successfully called pricing'); },
dataType: 'json'
});
The post successfully hits the breakpoint in my PricingController's Create method. In reviewing my Request.QueryString, it is empty.
items is an array of SomeItem with length = 30. Defined as
function SomeItem(description, finalPrice, percentDiscount) {
this.Description = description;
this.FinalPrice = finalPrice;
this.PercentDiscount = percentDiscount;
}
I perform no JSON conversion because "javascript is JSON". How do I get to my data in the Pricing Controller?
JSON.stringify(items) runs I see a nice set of junk in my alert() (also pretty in Firebug):
[{"Description":"some item","Data2":"$1.00","data3":"10"},//...
But, when it arrives on the server...in C# Request.Form it looks like:
%5b%7b%22Description%22%3a%22some+item%22%2c%22data2%22 wtflip is that...
JSON is 'JavaScript Object Notation', not JavaScript. You use JSON to represent a JavaScript object, especially when you want to send it back to a server.
You do need to convert your JavaScript object to JSON before passing it to the ajax call - this should do the trick:
var json = $.toJSON(items);
Have a read of this, it might help: http://haacked.com/archive/2010/04/15/sending-json-to-an-asp-net-mvc-action-method-argument.aspx
Have you tried JSON.stringify() ?
You can change your data line to:
data: JSON.stringify(items),
If the target browser doesn't natively support JSON.stringify(), you can Google for a library to fill in that feature.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With