带有jQuery Ajax调用的MVC无法正确绑定空数组/可枚举 [英] MVC with jQuery Ajax call does not correctly bind empty array/enumerable

查看:85
本文介绍了带有jQuery Ajax调用的MVC无法正确绑定空数组/可枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个jQuery ajax调用,我试图在其中发送可以从复选框表中选择的用户的int ID.

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.

我没有选择任何用户的问题.我希望有一个空数组,但实际上我收到的是长度= 1的数组,其中包含userId 0(即,未分配的int值).

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;
}

断言失败是因为 numbers List< int>{0} .为什么绑定是这样发生的?

The Assert fails because numbers is List<int> { 0 }. Why is the binding happening like this?

推荐答案

我相信默认模型联编程序会将jQuery AJAX调用传递给它的空字符串转换为包含单个元素的整数数组,该元素包含整数(0)的默认值.如果您执行以下操作,您的代码将起作用-

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-

$('#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 }
    });
});

请参阅此问题以获取更多信息和替代解决方案-

See this question for further info and alternate solutions - How to post an empty array (of ints) (jQuery -> MVC 3)

这篇关于带有jQuery Ajax调用的MVC无法正确绑定空数组/可枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆