我一直在尝试从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:
[WebMethod]
public static bool PrintMessage(Message message)
{
try
{
...
return true
}
catch (Exception ex)
{
...
return false
}
}
我的错误是当我到达WebMethod时,消息对象为空。尽管它在客户端被填充如此:
{"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对象,
答案 0 :(得分:1)
调整您的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);
}
});
答案 1 :(得分:1)
Linting您提供的JSON对象(使用http://jsonlint.com/),它看起来好像&#34; message&#34;是一个数组/集合,所以反序列化将是一个小窍门。您应该将方法中的类型更改为:
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
}
}
我想知道该物业&#34;消息&#34;甚至实际上是需要的。