使用jQuery将复杂数据发送到C#

时间:2013-02-14 10:25:51

标签: c# ajax api query-string

我有一个JavaScript对象,所以我想发送到C#(问题在底部)

var data = {
    mykey1: "somevalue",
    mykey2: "somevalue2",
    addProducts: [
        {
            id: 1,
            quantity: 3,
            variation: 54
        },
        {
            id: 2,
            quantity: 5,
            variation: 23
        }
    ]
}

将单个产品或多个产品添加到用户购物篮中。我想发送一个对象数组..

我可以使用

在Javascript中访问它
data.addProducts[1].id

使用以下...

$.ajax({
    url: "/ajax/myurl",
    data: data,
    dataType: "json",
    type: "GET",
    success: function( response ){
        // Data returned as JSON
    }
});

它正在发送这样的数据(URL解码为您的阅读乐趣)

?mykey1=somevalue&mykey2=somevalue2&addProducts[0][id]=1&addProducts[0][quantity]=3&addProducts[0][variation]=54&addProducts[0][id]=2&addProducts[0][quantity]=5&addProducts[0][variation]=23

我的问题是......没有对数据使用JSON.stringify,只会将其作为完整对象发送到网址/ajax/myurl/{mykey1:1 ...}

如何从C#中读回这些信息? jQuery只是将它编码为标准方式,我应该对此做任何其他事情,是否有内置的方法在C#中获取这些数据?

1 个答案:

答案 0 :(得分:0)

var strValue = $(getStringValue);
var intValue = $(getIntValue)
$.ajax({
type: \"post\",
url: \"default.aspx/getData\",
data: \"{\'postedAjaxStringValue\"\': \'\" + encodeURIComponent(strValue) + \"\', postedAjaxIntValue: \" + encodeURIComponent(intValue ) + \"}\",
contentType: \"application/json; charset=utf-8\",
dataType: \"json\",
success: OnSuccess,
failure: function (response) {
error: function (response) {
});

// ON C#KodeBehind ..

[System.Web.Services.WebMethod]
public static string getData(string postedAjaxStringValue, int postedAjaxIntValue){}