0

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}""
1
  • You can, what you're passing probably just isn't in the format .net expects. Could you grab the output of JSON.stringify("{" + dataString + "}") and add to the question? Commented Mar 29, 2013 at 20:52

2 Answers 2

1

You are building a string with dataString, you should be building an object then converting that object to json. Something like

    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;
        }
    });
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, this worked. I'll accept this as an answer as soon as I can. Any other recommendations you might have?
Try reading this site a little bit... I think what you're doing is overkill. You don't need to send JSON strings, just send the object and let ASP.Net deserialize it. encosia.com/jquery-for-the-asp-net-developer (a collection of blogs about JQuery and ASP.Net)
Here's the specific article that helped me figure this out: encosia.com/…
1

I'm going to go ahead and add this as an answer: you're doing too much work yourself, let the framework do all that stuff!

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

Your AJAX call needs to just be this... no need to make a JSON string yourself!

    $.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;
        }
    });

And then on your back-end service, change the signature to something like this...

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

Only, use some struct or object that matches your JSON object. Don't do this work yourself. It did take me a couple days to get this figured out, but when you do, it's beauty.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.