【问题标题】:Send array to the controller发送数组到控制器
【发布时间】:2013-04-07 05:35:24
【问题描述】:

如何将数组发送到控制器? 我试过了:

window.location.href = "/SomeController/SomeMethod?fields=" + SomeArray;

等等:

window.location.href = "/SomeController/SomeMethod?fields[][]=" + SomeArray;

在控制器中我收到:

public ActionResult SomeMethod(int[][] fields) // here fields = null;
{
// Some code
}

【问题讨论】:

    标签: javascript asp.net-mvc


    【解决方案1】:

    使用 jQuery ajax method

    将js对象SomeArray转换为Json,并在ajax方法的data属性中传回控制器。下面我使用现代浏览器支持的 JSON.stringify,但您可以包含脚本json2 以支持旧浏览器。

                  $.ajax({
                        url: '/SomeController/SomeMethod',
                        type: 'POST',
                        data: JSON.stringify(SomeArray),
                        dataType: 'json',
                        contentType: 'application/json; charset=utf-8',
                        success: function (result) {
                            alert("Success");
                        },
                        error: function (xhr) {
                            alert(xhr.statusText + " Internal server error")
                        }
                    })
    

    【讨论】:

    • 调试服务器以找出错误所在。你的控制器动作被调用了吗?
    【解决方案2】:

    如果你使用 jQuery,试试jQuery.param

    var  data ={
    
        fields :[
            [
                'car',
                'bike'
            ]
        ]
    };
    
    window.location.href = 'SomeController/SomeMethod?'
                           + decodeURIComponent( $.param(data) );
    

    【讨论】:

    • fields 有 100 个参数 - 不实用。
    • @user2204438 你能展示一些SomeArray 包含的样本吗?所以我们可以给出更具体的答案!
    • SomeArray[10][10] 有 int 变量 {0 or 1 or 2 or 3} 就是这样
    猜你喜欢
    • 1970-01-01
    • 2021-12-17
    • 1970-01-01
    • 1970-01-01
    • 2014-02-11
    • 2013-09-26
    • 2018-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多