我在将 Javascript Ajax 与 ASP.NET Controller 类型匹配时遇到困难。所有参数都很好,除了 Controller 接收到的 MsgData 为 null 之外。
我的 Controller 类和代码:
public class AjaxMessage
{
public enum MsgStatusType : int { OK, NOK }
public string MsgType { get; set; }
public List<AjaxMessageItem> MsgData { get; set; }
public MsgStatusType MsgStatus { get; set; }
public string MsgStatusMsg { get; set; }
}
还有
public class AjaxMessageItem
{
public string Name { get; set; }
public string Value { get; set; }
public AjaxMessageItem()
{
Name = String.Empty;
Value = String.Empty;
}
}
最后:
public ActionResult Get(AjaxMessage ajaxMessage)
{
... do some stuff...
}
我的 Javascript 调用:
var url = '@Url.Action("Get", "AjaxServer")';
$.ajax({
url: url,
cache: false,
type: "POST",
data: {
'MsgType': 'MsgType1',
'MsgData': { 'Name': 'customerId', 'Value': 'current' },
'MsgStatus': 'OK',
'MsgStatusMessage' : ''
},
success: function (data) {
if (data.msgStatus != 'OK') {
var errorMsg = 'Error reading data.' + data.msgStatusMessage;
alert(errorMsg);
return;
}
... do some stuff...
}
},
error: function (data) {
alert('Error retrieving Ajax data.');
}
});
在 Controller 中,我在寻找 ajaxMessage 变量时得到了 MsgType
、MsgStatus
和 MsgStatusMsg
,但是 MsgData
始终为 null
并且应接收 customerId
数据。
我需要一些帮助来解决这个问题。请帮我找出缺少的内容...谢谢。
最佳答案
因为您要发送数组,所以必须使用 JSON.stringify
将对象显式转换为 JSON,将 MsgData 包装在 []
中并设置 contentType: 'application/json, charset=utf-8'
$.ajax({
url: url,
cache: false,
type: "POST",
contentType: 'application/json, charset=utf-8',
data: JSON.stringify({
'MsgType': 'MsgType1',
'MsgData': [{ 'Name': 'customerId', 'Value': 'current' }],
'MsgStatus': 'OK',
'MsgStatusMessage' : ''
}),
success: function (data) {
if (data.msgStatus != 'OK') {
var errorMsg = 'Error reading data.' + data.msgStatusMessage;
alert(errorMsg);
return;
}
... do some stuff...
}
},
error: function (data) {
alert('Error retrieving Ajax data.');
}
});
关于c# - Javascript Ajax 到 ASP.NET Controller 类 - 数组参数的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22396425/