0
我已經看到了人們做這件事的各種方式,但它仍然無法爲數組「comments」和「commentCriterions」設置值控制器。任何幫助將非常感激。如何使用Ajax(jquery)將數組發送到控制器(MVC)
編輯:我設法利用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'數組,然後查看它們是否包含數據。 – BFree 2015-02-11 21:23:32
除去ajax調用中參數名稱周圍的引號:ie data:{comments:comments,commentCriterions:commentCriterions,... etc ...} – itsme86 2015-02-11 21:34:46
對BFree - 是的,我用console.log()來測試值正在被設置正確。 – 2015-02-11 21:49:19