在我的网站中,我收集了一个数字列表(用于排序),并使用以下代码将它们发送到我的MVC操作:
$('#saveButton').click(function () {
var configId = $('#ConfigId').val();
var steps = new Array();
$('#stepList li').each(function (index) {
steps[index] = $(this).attr('stepId');
});
// Send the steps via ajax
$.ajax({
url: '" + Url.Action(MVC.GrmDeployment.EditStep.Reorder()) + @"',
type: 'POST',
dataType: 'json',
data: { configId: configId, stepIds: steps },
success: function (data) {
if (data.success) {
alert('Reorder was successful');
}
else {
alert(data.msg);
}
}
});
});
通过chrome我看到这通过网络发送以下数据:
configId:1
stepIds%5B%5D:3
stepIds%5B%5D:2
在我的控制器中,我有以下方法来接收值
public virtual ActionResult Reorder(int configId, ICollection<int> stepIds) { }
问题是stepIds
集合为空。有人看到任何理由吗?
答案 0 :(得分:1)
var viewModel = new Object();
viewModel.configId = $('#ConfigId').val();
viewModel.steps = new Array();
data: { JSON.Stringify(viewModel) },
答案 1 :(得分:1)
我记得,jQuery改变了它在ajax
方法中对数组进行编码的方式,因此为了继续与MVC兼容,您必须将traditional
选项设置为true
:
$.ajax({
url: '@Url.Action(MVC.GrmDeployment.EditStep.Reorder())',
type: 'POST',
dataType: 'json',
traditional: true, // This is required for certain complex objects to work with MVC AJAX.
data: { configId: configId, stepIds: steps },
success: function (data) {
if (data.success) {
alert('Reorder was successful');
}
else {
alert(data.msg);
}
}
});
答案 2 :(得分:0)
我有绑定到数组的动作。我个人有一个带有string []参数的动作。
尝试
public virtual ActionResult Reorder(int configId, int[] stepIds) { }