Passing chosen multi select values to controller action

前提是你 提交于 2019-12-21 16:22:44

问题


I'm trying to send the selected values of a chosen multi select list to an Action in my Controller. I've verified val() does show me an array of selected values like ["33","175"] when I print out to the console but the Action's argument is always null. I tried changing the argument type to object and verified it's not null but I can't parse the values. Any suggestions? Please and thanks!

Ajax call:

$(".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");
            }
        }
    });
});

Controller Action:

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

回答1:


you have to set traditional property of ajax to 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");
            }
        }
    });

you can also set it globally so there is no need to specify it in every ajax call:

$.ajaxSetup({
    traditional:true
   });

UPDATE:

Following is the reason why you need to set traditional:true:

jQuery 1.4 adds support for nested param serialization in jQuery.param, using the approach popularized by PHP, and supported by Ruby on Rails. For instance, {foo: ["bar", "baz"]} will be serialized as “foo[]=bar&foo[]=baz”.

In jQuery 1.3, {foo: ["bar", "baz"]} was serialized as “foo=bar&foo=baz”. However, there was no way to encode a single-element Array using this approach. If you need the old behavior, you can turn it back on by setting the traditional Ajax setting (globally via jQuery.ajaxSettings.traditional or on a case-by-case basis via the traditional flag).

Details can be seen jQuery 1.4 Released – Full Release Notes in Ajax section.

You can also see the explanation here. jQuery 1.4 breaks ASP.Net MVC actions with array parameters

Also see: jQuery 1.4 breaks ASP.NET MVC parameter posting



来源:https://stackoverflow.com/questions/25086481/passing-chosen-multi-select-values-to-controller-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!