为什么我的MVC动作不是模型绑定我的集合
本文关键字:我的 模型 绑定 集合 MVC 为什么 | 更新日期: 2023-09-27 18:09:16
在我的网站上,我收集了一组数字(用于排序),并将它们发送到我的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
集合为空。有人知道原因吗?
我记得,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);
}
}
});
使用JSON。Stringify:
var viewModel = new Object();
viewModel.configId = $('#ConfigId').val();
viewModel.steps = new Array();
data: { JSON.Stringify(viewModel) },
我已经将动作绑定到数组。我个人有一个带有字符串[]参数的操作。
试
public virtual ActionResult Reorder(int configId, int[] stepIds) { }