Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

javascript - Sending JSON object successfully to ASP.NET WebMethod, using jQuery

I've been working on this for 3 hours and have given up. I am simply trying to send data to an ASP.NET WebMethod, using jQuery. The data is basically a bunch of key/value pairs. So I've tried to create an array and adding the pairs to that array.

My WebMethod (aspx.cs) looks like this (this may be wrong for what I'm building in JavaScript, I just don't know):

[WebMethod]
public static string SaveRecord(List<object> items)
{
    ...
}

Here is my sample JavaScript:

var items = new Array;

var data1 = { compId: "1", formId: "531" };
var data2 = { compId: "2", formId: "77" };
var data3 = { compId: "3", formId: "99" };
var data4 = { status: "2", statusId: "8" };
var data5 = { name: "Value", value: "myValue" };

items[0] = data1;
items[1] = data2;
items[2] = data3;
items[3] = data4;
items[4] = data5;

Here is my jQuery AJAX call:

var options = {
    error: function(msg) {
        alert(msg.d);
    },
    type: "POST",
    url: "PackageList.aspx/SaveRecord",
    data: { 'items': items },
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    async: false,
    success: function(response) {
        var results = response.d;
    }
};
jQuery.ajax(options);

I get the error:

Invalid JSON primitive: items.

So, if I do this:

var DTO = { 'items': items };

and set the data parameter like this:

data: JSON.stringify(DTO)

Then I get this error:

Cannot convert object of type u0027System.Stringu0027 to type u0027System.Collections.Generic.List`1[System.Object]u0027
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In your example, it should work if your data parameter is:

data: "{'items':" + JSON.stringify(items) + "}"

Keep in mind that you need to send a JSON string to ASP.NET AJAX. If you specify an actual JSON object as jQuery's data parameter, it will serialize it as &k=v?k=v pairs instead.

It looks like you've read it already, but take another look at my example of using a JavaScript DTO with jQuery, JSON.stringify, and ASP.NET AJAX. It covers everything you need to make this work.

Note: You should never use JavaScriptSerializer to manually deserialize JSON in a "ScriptService" (as suggested by someone else). It automatically does this for you, based on the specified types of the parameters to your method. If you find yourself doing that, you are doing it wrong.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...