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

后端 未结 4 1195
不知归路
不知归路 2020-12-17 23:07

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 b

相关标签:
4条回答
  • 2020-12-17 23:54

    This is NOT valid JSON: { 'foo': 'bar' }

    Isn't, wasn't ever, never will be. JSON processors are often very forgiving, which of course is a false convenience.

    Read the specification. A string is defined to be enclosed in double quotes, not single quotes, not smiley face characters, not pieces of metal bent at right angles, not bricks. There's no mention of single quotes, period.

    Now, property names are JSON strings. By definition, they MUST are enclosed in double quotes.

    Valid: { "foo": "bar" } valid" { "foo": 100 } valid: { "foo": true } valid: { "foo": [ "one", "two" ], "bar": false }

    see www.json.org

    see www.jsonlint.com

    0 讨论(0)
  • 2020-12-17 23:56

    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().

    0 讨论(0)
  • 2020-12-18 00:06

    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.

    0 讨论(0)
  • 2020-12-18 00:07

    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,
    ...
    
    0 讨论(0)
提交回复
热议问题