【发布时间】:2015-02-11 21:14:43
【问题描述】:
我见过人们做这件事的各种方法,但仍然无法在控制器中设置数组“cmets”和“commentCriterions”的值。任何帮助将不胜感激。
编辑:我设法使用 JSON.stringify
data: {
'comments': JSON.stringify(comments),
数组已设置,但设置错误
comments[0] = "[\"zxczxczx\",\"Another boring comment\",\"Why is this broken?!\",\"GASP!\"]"
jQuery
function saveComment(popupId) {
var textArea = popupId.find('@commentClass');
var comments = [];
var commentCriterions = [];
for (var i = 0; i < textArea.length; i++) {
comments[i] = textArea.val();
commentCriterions[i] = textArea.attr("data-criterionid");
}
$.ajax({
url: "SaveComment",
method: "post",
dataType: 'json',
traditonal: true,
data: {
'comments': comments,
'commentCriterions': commentCriterions,
'observationId': observationId,
'reviewingId': '@reviewingId'
},
success: function (status) {
if (status == "False") {
alert("The ID number of the person currently being reviewed has changed, please refresh the page and try again. Any changes to this observation will not be saved.")
}
},
})
}
控制器
public bool SaveComment(string[] comments, string[] commentCriterions, string observationId, string reviewingId)
{
int breakPoint = 0;
return true;
}
在弄乱函数后,ajax 调用看起来像这样,在 ajax 中设置 contentType 后导致 500(内部服务器错误)。
$.ajax({
type: "POST",
url: "SaveComment",
dataType: "json",
data: {
'comments': JSON.stringify(comments),
'commentCriterions': JSON.stringify(commentCriterions),
'observationId': JSON.stringify(observationId),
'reviewingId': JSON.stringify('986509040'),
},
contentType: 'application/json; charset=utf-8',
traditonal: true,
success: function (status) {
if (status == "False") {
alert("The ID number of the person currently being reviewed has changed, please refresh the page and try again. Any changes to this observation will not be saved.")
}
},
})
【问题讨论】:
-
您确定您的 javascript 获得了您期望的值吗?在通过网络发送之前注销
comments和commentCriterions数组,看看它们是否有数据。 -
去掉 ajax 调用中参数名称的引号:即 data: { cmets: cmets, commentCriterions: commentCriterions, ...etc... }
-
To BFree - 是的,我使用 console.log() 来测试这些值是否设置正确。
-
需要在ajax选项中设置
contentType: "application/json; charset=utf-8",。 -
您还需要对数据进行字符串化。例如
var data = { comments: comments, commentCriterions: commentCriterions, ..};然后data: JSON.stringify(data),
标签: c# jquery ajax json asp.net-mvc