I am trying to simply pass some values from Javascript into my codebehind for processing.
I just want to pass a Number
and Message
to the WebMethod
but get different errors based on whatever thing I change.
JS:
function SendMessage() {
var number = document.getElementById("number").value;
var message = document.getElementById("message").value;
var msg = {
"Number": number,
"Message": message
};
$.ajax({
type: "POST",
url: "Default.aspx/SendMessage",
data: JSON.stringify(msg),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("Message sent");
},
error: function (msg) {
alert("Message call failed");
}
});
}
In my codebehind I have a WebMethod
defined and also a Message
class to hold my message
[WebMethod]
public static void SendMessage(string message)
{
//Create a TMessage and deserialize to it
}
Message
:
public class TMessage
{
public string Number { get; set; }
public string Message { get; set; }
}
My understanding is that I am receiving JSON and should deserialize it to a Message
type.
However I have a breakpoint in the SendMessage
method and it never gets hit, the error being returned is:
Message=Invalid web service call, missing value for parameter: 'message'.
From some playing around earlier, I was able to get the breakpoint hit by changing the parameter from string
to object
(and some changes to the data: value in the Ajax call), but then it seemed I was receiving a Dictionary
and I couldn't cast it to TMessage
.
Thanks for any suggestions.
If you clearly look at webmethod , it has only one param i.e. message
.
You need to pass this to ajax call. - var params = "{'message':'" + message + "'}";
Helpful link - Send JSON to webmethod?
function SendMessage() {
var number = document.getElementById("phonenumber").value;
var message = document.getElementById("message").value;
var params = "{'message':'" + message + "', 'number':'" + number + "'}";
$.ajax({
type: "POST",
url: "Default.aspx/SendMessage",
data: params,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("Message sent");
},
error: function (msg) {
alert("Message call failed");
}
});
}