jquery-ajax を介して呼び出したい次のWeb メソッドがあります。
[System.Web.Services.WebMethod]
public static int saveDataToServer(string cntName, string cntEmail, string cntMsg)
{
// Implementation
}
これは私のjquery ajax呼び出しメソッドです...
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;
}
メソッドを呼び出す前に、配列を渡しています。
var arrOfObjects = new Array("cntName", "cntEmail", "cntMsg");
var arrOfObjectVals = new Array($(cntName).val(),$(cntEmail).val(),$(cntMsg).val());
しかし、実際の呼び出しが発生すると、 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"}
メソッドで「文字列型データ」を辞書に変換する際に問題が発生していると思います。しかし、そもそもなぜそうなのでしょうか?Web メソッドに動的に渡したいデータを作成できませんか?
リクエストに応じて更新:
>> JSON.stringify("{" + dataString + "}")
""{cntName:asdasdasd,cntEmail:abijeet.p@osmosys.asia,cntMsg:saveDataToServersaveDataToServersaveDataToServersaveDataToServersaveDataToServersaveDataToServersaveDataToServer}""