我正在尝试使用 Ajax 发布多个数组到我的控制器。首先我有一个这样的模型:
public class EnrollmentOptionsVM
{
public virtual string OptionID{ set;get;}
public virtual string UserChoice { set;get;}
public virtual string TchOptionID { set; get; }
public virtual string TeacherChoice { set; get; }
}
然后我的脚本:
<script type="text/javascript">
var $checkboxes = $('input[type="checkbox"]');
var $strInstructors = $('input[name="instructorString"]');
$(document).ready(function () {
$('#saveBtn').click(function () {
var teacherOptions = [];
var options = [];
$.each($checkboxes, function () {
if ($(this).is(':checked')) {
var item = { "UserChoice": "checked", "OptionID": "YouCanSetIDHere" };
}
else {
var item = { "UserChoice": "unchecked", "OptionID": "YouCanSetIDHere" };
}
options.push(item);
})
$.each($strInstructors, function () {
if ($(this).is(':selected')) {
var tchItem = { "TeacherChoice": "checked", "TchOptionID": "SetTchIDHere" };
}
else {
var tchItem = { "TeacherChoice": "unchecked", "TchOptionID": "SetTchIDHere" };
}
options.push(tchItem);
})
$.ajax({ type:
'POST', url: '@Url.Action("EnrollmentRefresh", "Student")',
contentType: 'application/json',
data: JSON.stringify({firstArray:options, secondArray:teacherOptions})
}).done(function (html) {
});
});
});
</script>
在我的控制器中,这是动作签名:
[HttpPost]
public ActionResult EnrollmentRefresh(List<EnrollmentOptionsVM> checkedOptions)
{}
当我只发送这样的选项时:data: JSON.stringify(options)… 它可以工作,但是当我尝试像上面的代码一样发送多个数组时,它在控制器中返回 null。如何使用 JSON.stringify() 发布多个数组?
更新 1
<script type="text/javascript">
var $checkboxes = $('input[type="checkbox"]');
var $strInstructors = $('input[name="instructorString"]');
$(document).ready(function () {
$('#saveBtn').click(function () {
var teacherOptions = [];
var options = [];
$.each($checkboxes, function () {
if ($(this).is(':checked')) {
var item = { "UserChoice": "checked", "OptionID": "YouCanSetIDHere" };
}
else {
var item = { "UserChoice": "unchecked", "OptionID": "YouCanSetIDHere" };
}
options.push(item);
})
$.each($strInstructors, function () {
if ($(this).is(':selected')) {
var tchItem = { "TeacherChoice": "checked", "TchOptionID": "SetTchIDHere" };
}
else {
var tchItem = { "TeacherChoice": "unchecked", "TchOptionID": "SetTchIDHere" };
}
teacherOptions.push(tchItem);
})
$.ajax({ type:
'POST', url: '@Url.Action("EnrollmentRefresh", "Student")',
contentType: 'application/json',
data: JSON.stringify({checkedOptions:options,selectedTeacher:teacherOptions})
}).done(function (html) {
});
});
});
</script>
在控制器中:
[HttpPost]
public ActionResult EnrollmentRefresh( List<EnrollmentOptionsVM> checkedOptions, List<TeacherOptionMV> selectedTeachers)
{}
两个 ViewModels public class TeacherOptionMV {
public virtual string TchOptionID { set; get; }
public virtual string TeacherChoice { set; get; }
}
和
public class EnrollmentOptionsVM
{
public virtual string OptionID{ set;get;}
public virtual string UserChoice { set;get;}
}