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

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

[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"}"

share|improve this question
And what problem are you experiencing (more specifically)? – Mario Nov 19 '12 at 7:11

3 Answers

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

data: JSON.stringify(jsonObjects),
share|improve this answer
when performing your change i am getting the following" "{"Message":"Type \u0027System.Collections.Generic.IDictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]\u0027 is not supported for deserialization of an array.","StackTrace":" at System.Web.Script.Serialization.ObjectConverter.ConvertListToObject(IList list, Type type, JavaScriptSerializer serializer, Boolean throwOnError, IList& convertedList – user829174 Nov 19 '12 at 7:20
@user829174 I don't know much about asp.net but it looks like your webmethod is expecting an object and getting an array. – Musa Nov 19 '12 at 7:23
thank you for your feedback, to what should i change the signature of my method so i will be able to send that particular JSON object to the server, can you share a code? – user829174 Nov 19 '12 at 7:27

Pass your entire JSON as a string, like this:

data: '{variable: "value"}'

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

share|improve this answer
can you please give a code example. thanks – user829174 Nov 19 '12 at 7:21
Keys need to be quoted also. – Musa Nov 19 '12 at 7:24
I don't get errors if I leave the keys unquoted. – Yatrix Nov 19 '12 at 14:27

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:

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]
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:

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

    });
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.