Post JavaScript array with AJAX to asp.net MVC controller

Solution 1:

You could define a view model:

public class AddUserViewModel
{
    public int ProjectId { get; set; }
    public int[] userAccountIds { get; set; }
}

then adapt your controller action to take this view model as parameter:

[HttpPost]
public ActionResult AddUsers(AddUserViewModel model)
{
    ...
}

and finally invoke it:

function sendForm(projectId, target) {
    $.ajax({
        url: target,
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({ 
            projectId: projectId, 
            userAccountIds: [1, 2, 3] 
        }),
        success: ajaxOnSuccess,
        error: function (jqXHR, exception) {
            alert('Error message.');
        }
    });
}

Solution 2:

In JS:

var myArray = new Array();
myArray.push(2);
myArray.push(3);
$.ajax({
            type: "POST",
            url: '/MyController/MyAction',
            data: { 'myArray': myArray.join() },
            success: refreshPage
        });

In MVC/ C#:

public PartialViewResult MyAction(string myArray)
{
   var myArrayInt = myArray.Split(',').Select(x=>Int32.Parse(x)).ToArray();
   //My Action Code Here
}