0

EDIT2: Found the solution, please see JSON, AJAX, and ASP.NET

The problem ended up being that the parameter in the ajax call is NOT sent to the WebMethod on the server side as a string. The JSON string in the data field of the ajax call is actually converted to the object type specified in the WebMethod's parameter. That being said, my problem was that the data was not being passed into the WebMethod as a string, but a different object type.

EDIT: Looking at the browser console in Chrome, i'm getting this error: Failed to load resource: the server responded with a status of 500 (Internal Server Error). Digging in deeper, I have the following response:

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

The following ajax call is never executed, and it seems like the data parameter does not have a valid value. If data is set equal to a string literal with valid JSON, there is no problem. There just seems to be an issue converting javascript objects into a valid parameter for data in the ajax call. Please see the below code snippet in my aspx file:

<script type="text/javascript">
        $(document).ready((function () {
            $('#mytable tr').click(function (event) {
                var array = [];
                $(".tdval").each(function () { 
                    array.push({
                        value: $(this).html()
                    });
                });
                alert(JSON.stringify(array)); //produces what appears to be valid json after calling stringify: [{"value":"val1"},{"value":"val2"}]

                $.ajax({
                    type: "POST",
                    url: "schedule.aspx/GetCurrentTime",
                    data: JSON.stringify({ array }), //this seems to be the issue
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response){
                        alert(response.d + "lol");
                    },
                    complete: function () {
                        alert("complete");
                    }
                });
            });
        }));
    </script>

And this is the method in the C# code behind that the ajax call posts to:

    [System.Web.Services.WebMethod]
    public static string GetCurrentTime(string name)
    {
        return "Hello ";
    }

Interestingly, I am able to change data: JSON.stringify({ array }) in the ajax call to some random json as a string literal and it works fine as it should. But when using stringify, the "success" callback method from the ajax call is never executed. Any thoughts?

2
  • 2
    Why are there curly braces in the second stringify call? Dont think these are required.. Commented Dec 29, 2017 at 20:00
  • { array } is ES6 shorthand for { array: array }. So the JSON will have the array in the "array" property of the JSON object. Is that what the controller expects? Commented Dec 29, 2017 at 21:14

1 Answer 1

0

You have the array inside an object when you call JSON.stringify(), so the JSON you're sending will look like:

{ array: [{"value":"val1"},{"value":"val2"}] }

instead of what you alerted earlier in the function.

Instead, use:

data: JSON.stringify(array),
Sign up to request clarification or add additional context in comments.

13 Comments

Still not working after removing the curly brackets. It was actually unintentional to use those, it was a remnant from troubleshooting. I used JSONLint to test whether the JSON is valid or not and it's saying it is. Any other suggestions?
Have you looked in the Network tab of the console to see if the AJAX request is being sent, what the parameters are, and what the response from the controller is?
When I use the string literal '{"name":"Bob"}' the code works. But using [{"value":"val1"},{"value":"val2"}] does not work despite JSONLint saying its valid JSON. I updated my code to show the C# codebehind method that this data is passed to as well so that all the code is available.
What Network tab? In browser or visual studio? I'm not familiar with monitoring what the parameters are outside of putting it in the debug console.
I'm talking about the browser console. Anyone working on browser applications should become familiar with the browser's developer tools console.
|

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.