I am attempting to pass JavaScript values into my codebehind for processing, encountering various errors as I try different approaches.
I am trying to send a Number
and Message
to the WebMethod
.
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 the codebehind, I have defined a WebMethod
and a Message
class to store 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; }
}
I expected to receive JSON and deserialize it to a Message
type, but my breakpoint in the SendMessage
method is not hit. The error message says:
Message=Invalid web service call, missing value for parameter: 'message'.
After some experimentation, changing the parameter from string
to object
allowed the breakpoint to be hit (with changes to the data: value in the Ajax call). However, it appeared that I was receiving a Dictionary
instead of being able to cast it to TMessage
.
Any suggestions are appreciated.