WebMethod无法捕获通过ajax发送的对象
本文关键字:ajax 对象 WebMethod | 更新日期: 2023-09-27 18:00:41
我一直在尝试用JavaScript从客户端获取一个对象,并将其发送到C#WebMethod进行处理。到目前为止,我还无法获得WebMethod来成功处理传入的json对象。
我的JavaScript:
var _Messages;
function callData() {
var timeNow = new Date;
$.ajax({
type: "POST",
url: "Default.aspx/All",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {_Messages = data.d; Render(data.d); $('#updated_time').html("<p class='text'>Last Updated: " + ("0" + timeNow.getHours()).slice(-2) + ":" + ("0" + timeNow.getMinutes()).slice(-2) + ":" + ("0" + timeNow.getSeconds()).slice(-2) + "</p>") },
failure: function (response) {
alert(response.d);
}
});
}
function printFunction() {
var listofmsg = $.grep(_Messages, function(a) {
return a.Text.trim().replace(/'r'n|'r|'n/g, ' ') == $('#navigate tr td').eq(active*2-1).text().trim().replace(/'r'n|'r|'n/g, ' ');
});
listofmsg[0].Text = listofmsg[0].Text.replace(/'r'n|'r|'n/g, ' ');
var msg = listofmsg[0];
//var input = {TimeStamp: msg.Text, TimeSet: msg.TimeSet, Text: msg.Text, Type: msg.Type, IsGreen: msg.IsGreen}
console.log(JSON.stringify({'message':msg}));
$.ajax({
type: "POST",
url: "Default.aspx/PrintMessage",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({ 'message' : msg}),
success: function (data) { console.log(data.d);},
failure: function (response) {
alert(response.d);
}
});
}
我的目标:
public class Message
{
public string TimeStamp { get; set; }
public DateTime TimeSet { get; set; }
public string Text { get; set; }
public string Type { get; set; }
public bool IsGreen { get; set; }
public Message(string timestamp, DateTime timeset, string text, string type, bool isgreen)
{
TimeStamp = timestamp;
TimeSet = timeset;
Text = text;
Type = type;
IsGreen = isgreen;
}
}
我的网络方法:
[WebMethod]
public static bool PrintMessage(Message message)
{
try
{
...
return true
}
catch (Exception ex)
{
...
return false
}
}
我的错误是,当我到达WebMethod时,消息对象为null。尽管它在客户端是这样填写的:
{"message":[{"TimeStamp":"08:39:28","TimeSet":"/Date(1398727057151)/","Text":"TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST ","Type":"spc","IsGreen":true}]}
有什么问题吗?我的最佳猜测是我没有正确格式化json对象,
Linting您提供的JSON对象(使用http://jsonlint.com/)并且它看起来好像"message"是一个数组/集合,因此取消序列化将有点困难。您应该将方法中的类型更改为:
public static bool PrintMessage(List<Message> message)
或者删除JSON对象声明中的数组声明([]括号)并保留相同的签名,即
public static bool PrintMessage(Message message)
JSON对象修改为:
{
"message": {
"TimeStamp": "08:39:28",
"TimeSet": "/Date(1398727057151)/",
"Text": "TEST TEST TEST TEST TEST",
"Type": "spc",
"IsGreen": true
}
}
我想知道是否真的需要属性"消息"。
调整您的ajax帖子以使用
$.ajax({
type: "POST",
url: "/PrintMessage",
contentType: "application/json",
data: JSON.stringify({ 'message' : msg}),
success: function (data) { console.log(data.d);},
failure: function (response) {
alert(response.d);
}
});