在select2 jquery插件的数据部分传递数组

时间:2013-03-05 15:12:53

标签: jquery asp.net-mvc-3 knockout.js jquery-select2

我在使用Select2 jquery插件(使用MVC3,Razor和Knockout JS)以及我希望传递给我的ajax调用的自定义参数时遇到问题。

我有这段代码:

$('#QuickSearchPresentation').select2({
        placeholder: "Search for a movie",
        minimumInputLength: 1,
        ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
            url: '@Url.Action("QuickSearchMainContainerFromPresentationByIdFolders", "DataCenter", new { amount = 10 })',
            contentType: 'application/json',
            dataType: 'json',
            type: 'POST',
            quietMillis: 400,
            data: function (term, page) {
                return ko.toJSON({
                    term: term,
                    idFolders: vm.Container.Catalogs
                });
            },
            results: function (data, page) { // parse the results into the format expected by Select2.
                // since we are using custom formatting functions we do not need to alter remote JSON data
                console.log('results', data);
                return {results: data};
            }
        },
        initSelection: function(element, callback) {

            console.log('element', element);

        },
        formatResult: containerQuickSearchResult, // omitted for brevity, see the source of this page
        formatSelection: containerQuickSearchResult,  // omitted for brevity, see the source of this page
        dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
        escapeMarkup: function (m) { return m; } // we do not want to escape markup since we are displaying html in results
    });

vm是来自knockout js的模型,而Catalogs是一个int数组。

问题是我无法将idFolders数组传递给我服务器上的Action,服务器响应“”值不能为null。参数名称:source“(因为数组在我的控制器中的Action上变为null)。 我尝试一切可能的方式,我想,我找不到正确的方法。

我希望你能帮助我。

谢谢, 贡萨洛。

1 个答案:

答案 0 :(得分:0)

在您的jQuery ajax调用中,对于您的数据属性,请尝试将其包装在JSON.stringify()中。像这样:

data: function (term, page) {
    return JSON.stringify(ko.toJSON({
        term: term,
        idFolders: vm.Container.Catalogs
    }));
},

我注意到使用JSON.stringify包装数据会使MVC正确处理JSON。