简体   繁体   中英

Unable to Send JSON array to server

I Use the following to create a Json array in a $.each() method

JsonData.push({ "refpracid": refPracID, "Spec":funcSpec(refPracID), "FTE": funcFTE(refPracID) });

This function posts the data to server

 function PostDataToServer(Data, methodName) { var obj = JSON.stringify(Data); $.ajax({ type: "POST", data: obj, url: "FTE_ASP.aspx/" + methodName, // data: JSON.stringify(obj), contentType: "application/json; charset=utf-8", dataType: "json", success: function (result) { if (result.d == "null") { RedirectToLogin(); } else { SetValues(result); } }, error: function (result) { $('#loadingIndicator').hide(); alert("PostDatToServer: " + result.responseText); //RedirectToErrorPage(); } }); 

This is the generated JSON after Stringify

[{"refpracid":"2436","Spec":"ALLERGIST | EAR NOSE & THROAT","FTE":"56"}]

And this is my server side function

public static string UpdateFte(string[] refpracid,string[] Spec,string[] FTE)
{
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    SqlConnection con = new SqlConnection(sqlConnectionString);
    SqlCommand cmd = new SqlCommand();
    DataSet ds = new DataSet();
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.CommandText = "UpdateFTE";
    cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SqlCommandTimeOut"]);
    cmd.Parameters.Add("@refpracname", SqlDbType.VarChar).Value = "";
    cmd.Parameters.Add("@specname", SqlDbType.VarChar).Value = "";
    cmd.Parameters.Add("@fte", SqlDbType.VarChar).Value = "";
    cmd.Parameters.Add("@UserID", SqlDbType.Int).Value = SessionVariables.UserID;
    cmd.Connection = con;
    try
    {
        con.Open();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(ds);
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        con.Close();
        con.Dispose();
    }
    GridData gd = GetGridData(ds);
    return serializer.Serialize(gd);
}

But when I try to send data to server the server is rejecting my call with the following error message. I searched and rechecked but I could not understand why it was throwing this error.

{"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\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"}

Can anybody point out where it is going wrong? Please!

You don't want to convert the variable Data to string. If Data is of JSON format, remove the following line.

var obj = JSON.stringify(Data);

Otherwise use:

var obj = JSON.parse(Data);

Your JSON should be

{
"refpracid":["abc","xyz"],
"Spec":["abc","xyz"],
"FTE":["abc","xyz"],
}

Add these lines into your ajax:

processData: false,
contentType: false

Also, you can use FormData inside ajax. Example:

var refpracid = [];
//push something to refpracid

var spec = [];
//push something to spec

var fte = [];
//push something to fte

//create a formData
var formData = new FormData();

//append data
formData.append('refpracid', refpracid);
formData.append('Spec', spec);
formData.append('FTE', fte);

So, the ajax should be:

$.ajax({
   type: "POST",
   url: "FTE_ASP.aspx/" + methodName,
   data: formData,
   processData: false,
   contentType: false,
   success: function (result) {
      if (result.d == "null") {
         RedirectToLogin();
      }
      else {
         SetValues(result);
      }
   },
   error: function (result) {
      $('#loadingIndicator').hide();
      alert("PostDatToServer: " + result.responseText);
      //RedirectToErrorPage();
   }
});

Hope this help you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM