12

In a AJAX request to the server in MVC, how can I pass a list of id's to the controller's action function?

I accept with or without use of Html helpers.

I know MVC's model binder has no problem when it comes to simple types like int, string and bool.

Is it something like I have to use and array instead in the action?

I don't care if I have to use an array or List and even if the strings I int or strings I can always convert them. I just need them on the server. My List ids gives null at the moment.

Javascript:

var ids= [1,4,5];
// ajax request with ids..

MVC Action:

public ActionResult ShowComputerPackageBuffer(List<int> ids) // ids are null
{
    // build model ect..
    return PartialView(model);
}

EDIT: Added my AJAX request

$(document).ready(function () {
    $('#spanComputerPackagesBuffer').on('click', function () {
        var ids = $('#divComputerPackagesBuffer').data('buffer');
        console.log('bufferIds: ' + bufferIds);
        var data = {
            ids: ids
        };

        var url = getUrlShowComputerPackageBuffer();
        loadTable(url, "result", data);
    });
});

// AJAX's
function loadTable(url, updateTargetId, data) {
    var promise = $.ajax({
        url: url,
        dataType: "html",
        data: data
    })
    .done(function (result) {
        $('#' + updateTargetId).html(result);
    })
    .fail(function (jqXhr, textStatus, errorThrown) {
        var errMsg = textStatus.toUpperCase() + ": " + errorThrown + '. Could not load HTML.';
        alert(errMsg);
    });
};

// URL's
function getUrlShowComputerPackageBuffer() {
    return '@Url.Action("ShowComputerPackageBuffer", "Buffer")';
};

SOLUTIONS: // Thanks to @aherrick comment. I missed the good old "traditional"

$.ajax({
    type: "POST",
    url: '@Url.Action("ShowComputerPackageBuffer", "Buffer")',
    dataType: "json",
    traditional: true,
    data: {
        bufferIds: bufferIds
    }
});
radbyx
  • 9,352
  • 21
  • 84
  • 127

3 Answers3

22

Use the traditional parameter and set it to true.

$.ajax({
    type: "POST",
    url: "/URL",
    dataType: "json",
    traditional: true,
    data: {}
});
aherrick
  • 19,799
  • 33
  • 112
  • 188
8

Try this one (I've checked it):

$(function () {
        var ids = [1, 4, 5];
        $.ajax({
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            url: '@Url.Action("YourAction", "YourController")',
            data: JSON.stringify( { ids: ids })
        }).done(function () {

        });
    });

You have to make sure your contentType is application/json and your data is stringified.

MacGyver
  • 2,983
  • 1
  • 17
  • 14
  • I have tryed it, and bufferIds (or ids) is still null on server. How does your action signatur look like? – radbyx Mar 04 '15 at 13:51
1
public ActionResult SaveSomething(int[] requestData) 
//or
public ActionResult SaveSomething(IEnumerable<int> requestData)

Using Action Result you cannot receive JSON object:

Using Controler:

[HttpPost]
    [Route( "api/Controller/SaveSomething" )]
    public object SaveTimeSheet( int[] requestData )
    {
        try
        {
            doSomethingWith( requestData );

            return new
            {
                status = "Ok",
                message = "Updated!"
            };
        }
        catch( Exception ex )
        {
            return new
            {
                status = "Error",
                message = ex.Message
            };
        }


}

java script:

var ids = [1,4,5];
var baseUrl: 'localhost/yourwebsite'
$.ajax({
                    url: baseUrl + '/api/Controller/SaveSomething',
                    type: 'POST',
                    data: JSON.stringify(ids),
                    dataType: 'json',
                    contentType: 'application/json',
                    error: function (xhr) {
                        alert('Error: ' + xhr.statusText);
                    },
                    success: function (result) {
                        if (result != undefined) {
                            window.location.href = window.location.href;
                        }
                    },
                    async: false,
                });
SilentTremor
  • 4,747
  • 2
  • 21
  • 34