26 Sep 2011

jQuery Post a javascript array to ASP.NET MVC

I wanted to post a bunch of ID numbers to my MVC controller, which is sat waiting with the following signature:

public ActionResult UnParkLeads(IList<int> leadIds)


However, this post needed to be generated from jQuery - specifically we're sending through the data ids of entities that correspond to "checked" checkboxes in a list. So what we need was a way of iterating through the list of checked checkboxes, getting the IDs into an array, and sending that through ajax to the server, to be picked up with the correct signature action.

var leadIds = $('input.chkTileSelector:checked').map(function () {
                                                            return { name: 'leadIds', value: $(this).parents('div.Lead').data('id') };
                                                }).get();

$.ajax({
    url: '@Url.Action("UnParkLeads", "Lead")',
    type: 'POST',
    dataType: 'json',
    data: leadIds,
    success: function (result) {
        ReloadResultGrid();
    }
});    

The tricky bit was basically the construction of the javascript object literal in the map function: jQuery converts that array into the ajax querystring using its param() function, which requires name and value properties.

The result is that jQuery posts multiple values with the same name ('leadIds'), and MVC recognises that and converts them into an IList<int>.

No comments:

Post a Comment

Comments are very welcome unless you're a spammer, in which case you should probably kill yourself.

If I helped you out today, you can buy me a beer below. Cheers!