Chanchan
Chanchan

Reputation: 89

Pass and retrieve AJAX data to controller

I have this code in my view 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>

What it does is it sends an array object named clients (var clients) to my controller. For example, it passes an array object of ["Chan","John"]

Now in my controller, this is my code:

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

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

After the AJAX call, the controller returns a {data:null} object in the console log. What am I missing? I wanted to use the content of my clients object in my controller for returning a JSON data

Upvotes: 0

Views: 4725

Answers (1)

garry man
garry man

Reputation: 465

You must send a string version of JSON, here's some changes you should make

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

Upvotes: 1

Related Questions