传递和检索AJAX数据到控制器

时间:2019-02-10 11:24:51

标签: javascript jquery ajax asp.net-mvc

我的视图中有此代码 Index.cshtml

<script>
    var dropdown = $('#clientDropdown');
    dropdown.on('change', function () {
        var clients = dropdown.chosen().val();
        $.ajax({
            type: 'GET',
            url: '/Inventory/GetClient',
            datatype: 'json',
            data: {clients : clients},
            success: function (data) {
                console.log(data);
            }
        });
    });
</script>

它的作用是将名为 clients(变量客户端)的数组对象发送到我的控制器。例如,它传递 [“ Chan”,“ John”]

的数组对象

现在在我的控制器中,这是我的代码:

[HttpGet]
    public ActionResult GetClient()
    {
        var clients = Request.QueryString["clients"];

        return Json(new { data = clients }, JsonRequestBehavior.AllowGet);
    }

AJAX调用之后,控制器在控制台日志中返回一个 {data:null} 对象。我想念什么?我想使用控制器中 clients 对象的内容来返回JSON数据

1 个答案:

答案 0 :(得分:1)

您必须发送JSON的字符串版本,这是您应该进行的一些更改

var dropdown = $('#clientDropdown');
    dropdown.on('change', function () {
        var clients = dropdown.chosen().val();
        $.ajax({
            type: 'GET',
            url: '/Inventory/GetClient',
            contentType: 'application/json', // this
            datatype: 'json',
            data: {clients : JSON.stringify(clients)}, // and this
            success: function (data) {
                console.log(data);
            }
        });
    });