Review: Ajax POST to C# WebMethod

[WebMethod]
public static void testingWebMethod(Object dataTest)
{
Debug.WriteLine(dataTest);

Debug.WriteLine(dataTest);
}

 

var sendThisData = JSON.stringify({
dataTest: [{ "name": "foo" }]
});
$.ajax({
type: "POST",
url: "page.aspx/testingWebMethod",
data: sendThisData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
},
error: function () {
alert("Something went wrong.");
}
});
Advertisements

jQuery AJAX call to pass JSON to C# Method

(by AXDS)

Note: The C# method parameter needs to match the JSON key name.

C#:

[WebMethod]
public static void doSomethingCool(Object jsonDataName)
{
Debug.WriteLine(jsonDataName);
}

SCRIPT:

var jsonInnerData = {key1:value1,key2:value2};
var methodToCall = "webPage.aspx/doSomethingCool";
var jsonDataObject = JSON.Stringify({jsonDataName : jsonInnerData});

$.ajax({
type: 'POST',
url: methodToCall,
data: jsonDataObject,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function ()
{
alert('doSomethingCool executed.');
},
error: function (XMLHttpRequest, textStatus, errorThrown)
{
alert("Status: " + textStatus); alert("Error: " + XMLHttpRequest.responseText);
}
});