[英]Javascript Ajax to ASP.NET Controller class - array of array parameter
我在将Javascript Ajax与ASP.NET控制器类型匹配时遇到困难。 所有参数都可以正常使用,但控制器收到时MsgData为空。
我的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.');
}
});
在控制器中,我正在寻找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.');
}
});
您的数据被发送到服务器,但您无法正确获取,您可以检查浏览器的network
选项卡,或检查数据是否已通过以下方式发送到服务器:
HttpUtility.UrlDecode(Request.Form.ToString())
我认为最简单的方法是始终对您的数据进行stringify
,并将其deserializing
到服务器上的poco对象
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.