0
votes

I Want Pass json Object to WebMethod in aspx page

here's my jquery and WebMethod

$("#button-login").bind({
        Click: accountRegister
    });



function accountRegister(e) {

    var dataObj = $("#login input[type]").serializeArray();
    var obj = JSON.stringify(dataObj);
    $.ajax({
        type: "POST",
        url: "Checkout.aspx/login",
        data: obj,
        contentType: "application/json; charset=UTF-8",
        dataType: "json",

        beforSend: function () {
            $(this).attr("disabled", "true");
            $(this).after(waitObj);
        },

        success: function (msg) {
            // Replace the div's content with the page method's return.
            alert("success");
            $("#checkout").slideUp("slow");
            $("#payment-address").slideDown("slow");
        },
        error: function (msg) {
         //alert(msg);
        },
        complete: function (jqxhr,status) {
            alert("Type:" + $.type(jqxhr) + "\n Respons text: " + jqxhr.responseText + "\n status: " + status);

            $(this).attr("disabled", "false");
            $(".wait").remove();

        },
    });
}

my checkout.cs file

  namespace Ahooratech
    {

        public partial class Checkout : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {

            }

            [WebMethod]
            public static string login(string obj)
            { return "{data:data}";}

    }

i get this Errro:

Respons text: {"Message":"Type \u0027****System.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\u0026 convertedList)\r\n at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeInternal(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object\u0026 convertedObject)\r\n at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeMain(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object\u0026 convertedObject)\r\n at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)\r\n at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)\r\n at System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext context, JavaScriptSerializer serializer)\r\n at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"}

EDIT: Error represent a Type castiny but where is this casting? (I think there is a implicit type casting in JQuery)

EDITE: this is my obj Content in json form which send to server

"[{"name":"userName","value":"admin"},{"name":"password","value":"admin_"}]"

I figured This lines of accountRegister() to this:

var obj = JSON.Stringify({data:dataObj});

and in WebMethod modify to this:

public static string void login(Object data) {

}

and it works!

but i how can id Deserilize data

enter image description here

3

3 Answers

3
votes

Unfortunately you can not pass any array to a WebMethod as root object. You have to encapsulate data with a javascript object. Also your root object keys should match parameters of WebMethod.

If you want to pass an array, you can use that format.

JSON.stringfy({myArray: [1,2,3]})

In this case; your WebMethod signature should be like

[WebMethod]
public static void MethodName(IEnumerable<object> myArray);

The inner type of enumeration can be any type but parameter name should match with parameter name of json object.

0
votes

I suspect that you don't get an error when changing the paramater of the login function to type object.

Actually i would pass all parameters separately to the webmethod and not as one object.

0
votes

I Decorate my ajax method to this

 function accountRegister(e) {


    var data = $("#login input[type]").serializeArray();

    var str="[";
    $.each(data, function(index , value)
    {
        str += '{' + '"name"' + ":" + "\"" + value.name + "\"" + ', ' + '"value"' + ":" + "\"" + value.value + "\"" + '},';


    });
    // remove last char ","
    data = str.substr(0, str.length - 1);
   data += "]";

    $.ajax({
        type: "POST",
        url: "Checkout.aspx/login",
        data: JSON.stringify({ myData: data }),
        contentType: "application/json; charset=UTF-8",
        dataType: "json",
       // converts: {               "html text": function(data) { return $(data);}},
        //dataFilter: function(data,dataType) {           if(dataType == "json")        {    var dataFilter = $.parseJSON(data);        return data;              }              else return data;            },
        beforSend: function () {
            $(this).attr("disabled", "true");
            $(this).after(waitObj);
        },

        success: function (msg) {
            // Replace the div's content with the page method's return.
            alert("success");
          // $("#checkout").slideUp("slow");
           // $("#payment-address").slideDown("slow");
        },

and web method to this

public  class nameVal
    {
        public string name { get; set; }
        public string value { get; set; }
    }
    [WebMethod]
    public static string login(object myData)
    {

        JavaScriptSerializer js = new JavaScriptSerializer();
        List<nameVal> myformElement = js.Deserialize<List<nameVal>>(myData.ToString());

        return "";

    }