Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't jquery turn my array into a json string before sending to asp.net web method?

So far, I've only been passing javascript strings to my web methods, which get parsed, usually as Guids. but now i have a method that accepts an IList... on the client, i build this array of objects and then attempt to pass it like:

$.ajax({
  type: 'POST',
  url: 'personalization.aspx/SetPersonalization',
  data: "{'backerEntries':" + backerEntries + "}",
  contentType: 'application/json; charset=utf-8',
  dataType: 'json',
  success: postcardManager.SetPersonalizationComplete
});

The post:

{'backerEntries':[object Object],[object Object],[object Object]}

The error response:

Invalid JSON primitive: object.

For some reason, jquery doesn't seem to convert my array into a json string? Any ideas why? I tried putting [] around the backerEntries, and {}, as well as {[]} just in sheer desperation. Am I missing something obvious here?

like image 637
EvilSyn Avatar asked Oct 31 '08 23:10

EvilSyn


3 Answers

data: "{'backerEntries':" + backerEntries + "}",

..is the same as

data: "{'backerEntries':" + backerEntries.toString() + "}",

...which is pretty much useless. Use Duncan's suggestion if you just want to pass an encoded list of values with the name "backerEntries" in your querystring. If you want to JSON-encode the data, then get a JSON library and call JSON.stringify().

like image 90
Shog9 Avatar answered Sep 22 '22 14:09

Shog9


The data you are passing you are trying to pass it as a string already. If you want jQuery to transform it leave the whole thing as an object, e.g.

data:{backerEntries: backerEntries }

Assuming of course backerEntries is an array. jQuery should transform this and will append it to the querystring as that is its default behaviour. Your current code is relying on default JavaScript behaviour which won't by default convert an array into its string representation.

like image 41
Duncan Avatar answered Sep 25 '22 14:09

Duncan


Since you're using ASP.NET, you can use the built-in ASP.NET AJAX serialization library:

var backerEntriesJson = Sys.Serialization.JavaScriptSerializer.serialize(backerEntries);

then pass that directly in your jQuery ajax call:

...
data: backerEntriesJson,
...
like image 45
Herb Caudill Avatar answered Sep 24 '22 14:09

Herb Caudill