MVC 与 jQuery Ajax 调用无法正确绑定空数组/可枚举
我有一个 jQuery ajax 调用,其中我试图发送可以从复选框表中选择的用户的 int ID。
我遇到的问题是没有选择任何用户。我希望得到一个空数组,但实际上我收到一个 length = 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;
}
断言失败,因为 numbers
是 List
。为什么绑定会发生这样的情况?
I have a jQuery ajax call in which I am trying to send the int IDs of users which can be selected from a table of checkboxes.
I am having a problem with the case that no users are selected. I would expect an empty array but in fact I receive an array of length = 1, containing userId 0 (i.e. an unassigned int value).
The following snippet reproduces the problem
$('#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;
}
The Assert fails because numbers
is List<int> { 0 }
. Why is the binding happening like this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我相信默认模型绑定器会将 jQuery AJAX 调用传递给它的空字符串转换为一个整数数组,该数组包含单个元素,该元素包含整数的默认值 (0)。如果你做了这样的事情,你的代码就会工作 -
请参阅此问题以获取更多信息和替代解决方案 - 如何发布(整数)空数组(jQuery -> MVC 3)
I believe that the default model binder will convert the empty string that is passed to it by the jQuery AJAX call into a integer array that contains a single element containing the default value of an integer (0). Your code would work if you did something like this-
See this question for further info and alternate solutions - How to post an empty array (of ints) (jQuery -> MVC 3)