将所选的多选值传递给控制器​​操作

时间:2014-08-01 18:30:13

标签: c# jquery ajax asp.net-mvc jquery-chosen

我正在尝试将所选多选列表的选定值发送到控制器中的操作。我已经验证了val()确实显示了一个选定值的数组,如[“33”,“175”],当我打印到控制台但Action的参数始终为null。我尝试将参数类型更改为object并验证它不是null但我无法解析值。有什么建议?拜托,谢谢!

Ajax电话:

$(".chosen-select").on("change", function (event, params) {
    console.log($(".chosen-select").val());

    $.ajax({
        url: '@Url.Action("BDOReferralSourcesTableHTML","ReferralNetwork")',
        type: 'GET',
        dataType: 'json',
        cache: false,
        data: { bdoIds: $(".chosen-select").val() },
        success: function (response) {
            if (response.length > 0) {
                alert(response);
            }
            else {
                alert("response length zero");
            }
        }
    });
});

控制器操作:

public ActionResult BDOReferralSourcesTableHTML(string[] bdoIds)
{
    return Content("<b>test</b>", "text/html");    
}

1 个答案:

答案 0 :(得分:9)

您必须将ajax的traditional属性设置为true

$.ajax({
        url: '@Url.Action("BDOReferralSourcesTableHTML","ReferralNetwork")',
        type: 'GET',
        dataType: 'json',
        cache: false,
        traditional:true,
        data: { bdoIds: $(".chosen-select").val() },
        success: function (response) {
            if (response.length > 0) {
                alert(response);
            }
            else {
                alert("response length zero");
            }
        }
    });

您也可以全局设置它,因此无需在每次ajax调用中指定它:

$.ajaxSetup({
    traditional:true
   });

UPDATE:

以下是您需要设置 traditional:true

的原因
  
    

jQuery 1.4 使用PHP推广并由Ruby on Rails支持的方法,在 jQuery.param 中添加了对嵌套参数序列化的支持。例如, {foo: ["bar", "baz"]} 将被序列化为“foo [] = bar&amp; foo [] = baz”

         

jQuery 1.3 中, {foo: ["bar", "baz"]} 被序列化为“foo = bar&amp; foo = baz”。但是,使用这种方法无法对单元素阵列进行编码。如果您需要旧的行为,可以通过设置传统的Ajax设置(全局通过 jQuery.ajaxSettings.traditional 或通过传统标志逐个案例)将其重新打开。 / p>   

可以在 Ajax 部分中看到详细信息jQuery 1.4 Released – Full Release Notes

您还可以看到解释here. jQuery 1.4 breaks ASP.Net MVC actions with array parameters

另见: jQuery 1.4 breaks ASP.NET MVC parameter posting