Reputation: 1484
I'm trying to get data from a form on a button click and send it to a web method in my code behind. I'd like to pass it as a JSON object or at least I think that's the convention? Here's my current code however it generates an error (Shown below the code).
$("#addTask")
.click(function( event ) {
var newTask = new Object();
newTask.TaskName = $('#ctl00_ContentArea_taskName').val();
newTask.TaskDescription = $('#ctl00_ContentArea_taskDescription').val();
newTask.SQLObjectID = $('#ctl00_ContentArea_sqlReportingID').val();
newTask.WarehouseSQLObjectID = $('#ctl00_ContentArea_warehouseSQLObjectID').val();
$.ajax({
type: "POST",
url: 'AddTask.aspx/validateTask',
data: JSON.stringify(newTask),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success : function(data) {
alert( data.d );
}
});
});
__
{"Message":"Invalid web service call, missing value for parameter: \u0027newTask\u0027.","StackTrace":" at System.Web.Script.Services.WebServiceMethodData.CallMethod(Object target, IDictionary`2 parameters)\r\n at System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object target, IDictionary`2 parameters)\r\n at System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext context, WebServiceMethodData methodData, IDictionary`2 rawParams)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"}
I've tried having my web method in a bunch of different ways, such as but not limited to:
<System.Web.Services.WebMethod()> _
Public Shared Function validateTask(ByVal newTask As TaskBO)
Or with a bunch of individual parameters as strings.
What is the correct way to accomplish what I'm trying to do? What do I not understand about formatting JSON objects?
Thanks for your help!
Upvotes: 0
Views: 608
Reputation: 50905
The web service expects an item with the key "newTask" (as shown by your method's parameter). Your request will be sent as:
{
"TaskName": "stuff",
"TaskDescription": "stuff",
"SQLObjectID": "stuff",
"WarehouseSQLObjectID": "stuff"
}
But you really need it to be:
{
"newTask": {
"TaskName": "stuff",
"TaskDescription": "stuff",
"SQLObjectID": "stuff",
"WarehouseSQLObjectID": "stuff"
}
}
So change your $.ajax()
call to be:
data: JSON.stringify({
newTask: newTask
}),
contentType: "application/json; charset=utf-8",
Upvotes: 2
Reputation: 1269
If you are using a separate js file for this code to work, verify the client ids
If there are more properties on the class for the newTask, you can always exclude unnecessary properties from json object using delete operator.( for example: delete newTask.UnnecessaryProperty)
Upvotes: 0