构建要动态传递给jquery / ajax的数据

时间:2013-03-29 20:50:56

标签: c# asp.net ajax jquery

我希望通过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}""

2 个答案:

答案 0 :(得分:1)

您正在使用dataString构建字符串,您应该构建一个对象,然后将该对象转换为json。像

这样的东西
    var dataString = {};
    // Building data object, we know the two arrays have same length!
    for (var intIndex = 0; intIndex < arrOfObjName.length; ++intIndex) {
        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;
        }
    });

答案 1 :(得分:1)

我将继续将此作为答案添加:你自己做了太多工作,让框架完成所有这些工作!

http://encosia.com/asp-net-web-services-mistake-manual-json-serialization/

您的AJAX调用只需要这样......不需要自己制作JSON字符串!

    $.ajax({
        type: "POST",
        url: urlToCall,
        contentType: "application/json; charset=utf-8",
        data: arrOfOBJECTS, //looky here! 
        dataType: "json",
        success: function (data) {
            tempData = data;
        },
        error: function (data) {
            tempData = null;
        }
    });

然后在您的后端服务上,将签名更改为类似的内容......

[System.Web.Services.WebMethod]
public static int saveDataToServer(string[] myArray)
{
     // Implementation
}

仅使用一些与您的JSON对象匹配的结构或对象。不要自己做这项工作。我花了几天的时间来弄明白这一点,但是当你这样做时,它就是美丽的。