0

I'm trying to call a WebMethod via ajax with a JSON string as follows:

                let jsonData = JSON.stringify({test: "Test"});

                $.ajax({
                    type: "POST",
                    url: "WebForm.aspx/DoStuff",
                    data: '{data: "' + jsonData + '" }',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: OnSuccess,
                    failure: function (response) {
                        alert(response.d);
                    }
                });

However, I get a HTTP 500 internal error.

I would like to parse the JSON string in the WebMethod as I do not know the values at runtime. The WebMethod looks like this:

        [WebMethod]
        public static string DoStuff(string data)
        {
            var keyValuePairs = JsonConvert.DeserializeObject<Dictionary<string, string>>(data);
            foreach (var key in keyValuePairs.Keys)
            {
                ...
            }

            return ...
        }

2 Answers 2

1

Ok, the problem was with the formatting of the data in the ajax request. The following worked:

            let jsonData = JSON.stringify({test: "Test"});
            let data = { data: jsonData };

            $.ajax({
                type: "POST",
                url: "SomePage.aspx/DoStuff",
                data: JSON.stringify(data),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnSuccess,
                failure: function (response) {
                    alert(response.d);
                }
            });
Sign up to request clarification or add additional context in comments.

Comments

0

Try parsing the json data to a JObject if you're using newtonsoft, or a JSONDocument if you want to use Microsofts Json library in .net core 3 System.Text.Json

https://www.newtonsoft.com/json/help/html/ParseJsonObject.htm

https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to#use-jsondocument-for-access-to-data

Example using System.Text.Json

using (JsonDocument jsonDoc = JsonDocument.Parse(data))
{
    JsonElement root = jsonDoc.RootElement;
    JsonElement dataEl = root.GetProperty("Data");
    var testEl = dataEl.GetProperty("Test")
    ...
}

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.