【问题标题】:Passing chosen multi select values to controller action将选定的多选值传递给控制器​​操作
【发布时间】:2014-08-01 18:30:12
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案1】:

    你必须将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
       });
    

    更新:

    以下是需要设置traditional:true的原因:

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

    jQuery 1.3 中,{foo: ["bar", "baz"]} 被序列化为 “foo=bar&foo=baz”。但是,没有办法使用这种方法对单元素数组进行编码。如果您需要旧的行为,您可以通过设置传统的 Ajax 设置(全局通过 jQuery.ajaxSettings.traditional 或根据具体情况通过传统标志)将其重新打开。

    详情可以在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

    【讨论】:

    • 这很容易。有效!!谢谢你的链接
    • 很高兴能帮上忙..:)
    • 你先生,比北方事业的伟大领袖更伟大!
    • @banny 在我的帖子中我附上了详细描述的链接
    猜你喜欢
    • 2021-11-12
    • 1970-01-01
    • 2020-01-11
    • 1970-01-01
    • 2013-09-22
    • 1970-01-01
    • 2019-07-06
    • 1970-01-01
    • 2022-07-27
    相关资源
    最近更新 更多