如何使用ASP.NET WebMethod使用Ajax传递JSON对象

时间:2012-11-19 07:07:47

标签: asp.net ajax json jquery

我在使用Ajax和ASP.NET WebMethods

传递JSON对象时遇到问题
function setStudentInfo() {
    var jsonObjects = [
        { id: 1, name: "mike" },
        { id: 2, name: "kile" },
        { id: 3, name: "brian" },
        { id: 1, name: "tom" }
    ];

    $.ajax({
        type: "POST",
        url: "ConfigureManager.aspx/SetStudentInfo",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: false,
        data: { students: JSON.stringify(jsonObjects) },
        success: function (result) {
            alert('success');
        },
        error: function (result) {
            alert(result.responseText);
        }

    });
}

ASP.NET代码

[WebMethod]
public static void SetStudentInfo(object students)
{
     //Here I want to iterate the 4 objects and to print their name and id
}

我收到以下错误:

  

“{”消息“:”无效的JSON原语:学生。“,”StackTrace“:”在System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()      在System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32深度)         在System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input,Int32 depthLimit,JavaScriptSerializer serializer)            at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer,String input,Type type,Int32 depthLimit)               在System.Web.Script.Serialization.JavaScriptSerializer.Deserialize [T](字符串输入)                  在System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext上下文,JavaScriptSerializer序列化程序)                     在System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData,HttpContext context)                        在System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context,WebServiceMethodData methodData)“,”ExceptionType“:”System.ArgumentException“}”

5 个答案:

答案 0 :(得分:6)

将整个JSON作为字符串传递,如下所示:

data: '{variable: "value"}'

如果我尝试传递它,我总是会收到错误。

答案 1 :(得分:3)

我知道这是一个古老的问题,但如果有人来这里寻求答案,那就是解决方案;

var jsonObjects=[
    { id: 1, name: "mike" },
    { id: 2, name: "kile" },
    { id: 3, name: "brian" },
    { id: 1, name: "tom" }
];

$.ajax({
    type: "POST",
    url: "ConfigureManager.aspx/SetStudentInfo",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    async: false,
    data: JSON.stringify({ students: jsonObjects }),
    success: function (result) {
        alert('success');
    },
    error: function (result) {
        alert(result.responseText);
    }

});

答案 2 :(得分:2)

您收到该错误是因为需要单个Object但您的代码需要一个对象列表。有时这可能有点棘手。为了使数据传输更容易,您应该创建一个类,其中包含要传递给WebMethod的对象类型的属性,因为ASP.NET似乎更容易解析它。例如:

public class Student
{
    private string _name;
    private int _id;
    public string name {
        get { return _name; }
        set { _name = value; }
    }
    public int id {
        get { return _id; }
        set { _id = value; }
    }
}

然后您的WebMethod将更改为接受学生类对象列表,如下所示:

[WebMethod]
public static void SetStudentInfo(List<Student> Students)
{
    foreach (Student s in Students)
    {
        //Do whatever here System.Console.WriteLine(s.name);
    }
}

然后您需要做的就是稍微改变您的Ajax调用:

function setStudentInfo() {
    var jsonObjects = [
        { id: 1, name: "mike" },
        { id: 2, name: "kile" },
        { id: 3, name: "brian" },
        { id: 1, name: "tom" }
    ];

    $.ajax({
        type: "POST",
        url: "ConfigureManager.aspx/SetStudentInfo",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: false,
        data: { Students: JSON.stringify(jsonObjects) },
        success: function (result) {
            alert('success');
        },
        error: function (result) {
            alert(result.responseText);
        }

    });
}

答案 3 :(得分:1)

试试这段代码:

function setStudentInfo() {

var jsonObjects = {"students" : [
    { id: 1, name: "mike" },
    { id: 2, name: "kile" },
    { id: 3, name: "brian" },
    { id: 1, name: "tom" }
]};

$.ajax({
    type: "POST",
    url: "ConfigureManager.aspx/SetStudentInfo",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    async: false,
    data: JSON.stringify(jsonObjects),
    success: function (result) {
        alert('success');
    },
    error: function (result) {
        alert(result.responseText);
    }

});

}

答案 4 :(得分:0)

你实际上并没有将json发送到服务器,发送json只是为数据属性传递一个json字符串。

data: JSON.stringify(jsonObjects),