简体   繁体   中英

Reading a javascript object as JSON on POST

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?


Almost there. When 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.

Well, if you used the POST method, then it's not going to be in the QueryString variable. If you watch what is going on with a fiddler-like tool, is your data (items) being passed back in the body of the request? If so, then you should be able to access it. Otherwise, something is wrong with your AJAX request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM