我有一个jQuery ajax调用,其中我试图发送用户的int id,可以从复选框表中选择。
我遇到了一个没有选择用户的问题。我期望一个空数组,但实际上我收到一个长度= 1的数组,包含userId 0(即一个未分配的int值)。
下面的代码片段再现了问题
$('#test').click(function () {
var numbers = $('.noElements').map(function () {
// (selector does not match any elements, to demonstrate)
return 1;
}).get();
$.ajax({
url: '/MyController/Test',
type: "GET",
data: { numbers: numbers, count: numbers.length }
});
});
public ActionResult Test(IEnumerable<int> numbers, int count)
{
Assert(numbers.Count() == count);
return null;
}
Assert失败,因为numbers
是List<int> { 0 }
。为什么绑定是这样发生的?
我相信默认的模型绑定器会将jQuery AJAX调用传递给它的空字符串转换为一个整数数组,该数组包含单个元素,其中包含整数(0)的默认值。
$('#test').click(function () {
var numbers = $('.noElements').map(function () {
return 1;
});
if (numbers.length == 0) {
numbers = null;
count = 0;
}
else count = numbers.length;
$.ajax({
url: '/Home/Test',
type: "GET",
data: { numbers: numbers, count: count }
});
});
查看这个问题的进一步信息和替代解决方案-如何发布一个空数组(int) (jQuery ->MVC 3)