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

[英]How to pass JSON object using Ajax with ASP.NET WebMethod


I have a problem with passing a JSON object using Ajax and ASP.NET WebMethods

我使用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 code

ASP.NET代码

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

I am getting the following error:

我收到以下错误:

"{"Message":"Invalid JSON primitive: students.","StackTrace":" at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject() at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth) at 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) at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input) at System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext context, JavaScriptSerializer serializer) at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context) at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.ArgumentException"}"

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

5 个解决方案

#1


6  

Pass your entire JSON as a string, like this:

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

data: '{variable: "value"}'

数据:'{变量:“值”}'

I always get an error if I try to pass it as you have.

如果我试图通过它,我总是会收到错误。

#2


2  

You are getting that error because a single Object is expected but your code is expecting a List of Objects. This can be a bit tricky sometimes. To make the data transfer easier, you should create a class with properties for the type of object you want to pass to the WebMethod, because it seems to be easier for ASP.NET to parse that. For example:

您收到该错误是因为需要单个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; }
    }
}

And then your WebMethod will change to accept a List of Student Class Objects, like so:

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

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

Then all you need to do is slightly change your Ajax call like so:

然后你需要做的就是稍微改变你的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


2  

I know its an old question but if someone gets here for an answer here's the solution;

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

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);
    }

});

#4


1  

Try this code:

试试这段代码:

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);
    }

});

}

}

#5


0  

You aren't actually sending json to the server, to send json just pass a json string for the data property.

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

data: JSON.stringify(jsonObjects),

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2012/11/19/d1d3d52ef5859f02ad37da7d034c5971.html



 
© 2014-2018 ITdaan.com 粤ICP备14056181号