我在 MVC 3 中将 Javascript 数组传递给我的控制器时遇到了很大的麻烦。我不断收到空值,感觉我已经尝试了所有传递数组的方法。下面是 JavaScript、相关的视图模型Questions
和控制器签名。我会很感激任何帮助。我的 JavaScript 没有出现任何错误,我认为我一定遗漏了一些基本的东西。
控制器正确接收id
和的值。response-id
javascript
$("#form-submit-scores").submit(function () {
var question = [],
var item = [],
$('.questionRow').each(function (index) {
question[index] = new Array();
var fullQuestionId = $(this).attr('id');
var fullQuestionParts = fullQuestionId.split('-');
question[index].QuestionId = fullQuestionParts[fullQuestionParts.length - 1];
question[index].QuestionScore = $('.scoreBoard').val();
});
$('.itemRow').each(function (index) {
item[index] = new Array();
item[index].ItemId = $(this).attr('id');
item[index].ItemScore = $('.scoreBoard').val();
});
var url = "/ctr/SaveResponse",
data = {
Id: $('#id').val(),
ResponseId: $('#response-id').val(),
Questions: question,
Items : item
},
if (isSubmitScores) {
url = "/ctr/SubmitResponse"
}
$.ajax({
url: url,
type: 'Post',
data: data,
traditional:true,
datatype: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
if (!result.Success) {
....
....
....
视图模型
public class SubmitResponseViewModel
{
public int Id { get; set; }
public int ResponseId { get; set; }
IEnumerable<SubmitResponseScoresQuestionViewModel> Questions {get;set;}
IEnumerable<SubmitResponseScoresItemViewModel> Items { get; set; }
}
public class SubmitResponseScoresQuestionViewModel
{
public int QuestionId { get; set; }
public decimal? QuestionScore { get; set; }
}
控制器签名
public JsonResult SubmitResponseScores(SubmitResponseScoresViewModel model)
因此,正如我上面所说,我的模型现在包含正确的 and 值Id
,但and的response-id
值为空。我已经确认我正在 AJAX 调用中填充,所以我认为我没有为控制器提供适当格式的数据。Questions
Items
data
编辑:1
Chrome JS 调试器:AJAX 数据对象
JSON.stringify(data, null, 2)
"{
"Id": "1027",
"ResponseId": "26",
"Questions": [
{
"QuestionId": "7",
"QuestionScore": "0"
},
{
"QuestionId": "2",
"QuestionScore": "0"
},
{
"QuestionId": "1",
"QuestionScore": "0"
}
],
"Items": [
{
"ItemId": "434",
"ItemScore": "0"
}
]
}"