I have the following web method that I wish to call through jquery-ajax.
[System.Web.Services.WebMethod]
public static int saveDataToServer(string cntName, string cntEmail, string cntMsg)
{
// Implementation
}
This is my jquery ajax calling method...
function makeAjaxCall(arrOfObjName, arrOfObjValues, urlToCall) {
debugger;
var tempData;
// Check if objNames's length is same as objValues's length.
if (arrOfObjName.length != arrOfObjValues.length) {
return null;
}
var dataString = "";
// Building data object, we know the two arrays have same length!
for (var intIndex = 0; intIndex < arrOfObjName.length; ++intIndex) {
if (intIndex == arrOfObjName.length - 1) {
dataString += arrOfObjName[intIndex] + ":" + arrOfObjValues[intIndex];
continue;
}
dataString += arrOfObjName[intIndex] + ":" + arrOfObjValues[intIndex] + ",";
}
$.ajax({
type: "POST",
url: urlToCall,
contentType: "application/json; charset=utf-8",
data: JSON.stringify("{" + dataString + "}"),
dataType: "json",
success: function (data) {
tempData = data;
},
error: function (data) {
tempData = null;
}
});
return tempData;
}
Before calling the method, I'm passing it arrays,
var arrOfObjects = new Array("cntName", "cntEmail", "cntMsg");
var arrOfObjectVals = new Array($(cntName).val(),$(cntEmail).val(),$(cntMsg).val());
But when the actual call happens, I get the following error in Fiddler.
{"Message":"Cannot convert object of type \u0027System.String\u0027 to type \u0027System.Collections.Generic.IDictionary`2[System.String,System.Object]\u0027","StackTrace":" 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"}
I assume that the method is having problems converting the "string type data" to a dictionary. But why so in the first place? Can I not build the data that I wish to pass to the web-method dynamically ?
Updated as requested :
>> JSON.stringify("{" + dataString + "}")
""{cntName:asdasdasd,cntEmail:[email protected],cntMsg:saveDataToServersaveDataToServersaveDataToServersaveDataToServersaveDataToServersaveDataToServersaveDataToServer}""