Malcolm O'Hare
Malcolm O'Hare

Reputation: 4999

How to ajax/post JSON array to ASP MVC

Trying to do a post including some JSON data that has an array of integers in it. Pressing the button on my page to perform the post is getting to the action, but the expected data is not there (the two int[] variables are null). Doing a network profile while posting shows that the request body includes data like this:

groups%5B%5D=2&groups%5B%5D=3&alerts%5B%5D=5&alerts%5B%5D=9

Javascript:

$('#modal-save').click(function() { 
                var selectedGroups = [];
                var selectedAlerts = [];
                $('input:checked').filter('[data-group="true"]').each(function() {selectedGroups.push($(this).data('id')); });
                $('input:checked').filter('[data-group="false"]').each(function() {selectedAlerts.push($(this).data('id')); });
$.ajax({
                        type:'Post',
                        dataType: 'json',
                        url:'@Url.Action("UpdateAlertStores", new { alias = ViewBag.Alias})',
                        data: {groups: selectedGroups, alerts: selectedAlerts},
                    });

MVC Action:

[HttpPost]
public bool UpdateAlertStores(string alias, Guid? groupID, Guid? storeID, int[] groups, int[] alerts)
{
    return true;
}

Upvotes: 1

Views: 653

Answers (1)

AliRıza Adıyahşi
AliRıza Adıyahşi

Reputation: 15866

add traditional:true

traditional: true,
type:'Post',
dataType: 'json',
url:'@Url.Action("UpdateAlertStores", new { alias = ViewBag.Alias})',
data: {groups: selectedGroups, alerts: selectedAlerts},

after this changing your url looks like:

groups=2&groups=3&alerts=5&alerts=9

Upvotes: 3

Related Questions