Home > DeveloperSection > Forums > Post JavaScript array with AJAX to asp.net MVC controller
Manoj Bhatt
Manoj Bhatt

Total Post:153

Points:1079
Posted on    April-03-2013 2:17 AM

 ASP.NET MVC ASP.NET MVC 
Ratings:


 1 Reply(s)
 5210  View(s)
Rate this:
Hi Everyone!

My controller:

[HttpPost]
public ActionResult AddUsers(int projectId, int[] useraccountIds)
{
    ...
}
I'd like to post the parameters to the controller via AJAX. Passing the int projectId isn't a problem, but I can't manage to post the int[].

My JS code:

function sendForm(projectId, target) {
    $.ajax({
        traditional: true,
        url: target,
        type: "POST",
        data: { projectId: projectId, useraccountIds: new Array(1, 2, 3) },
        success: ajaxOnSuccess,
        error: function (jqXHR, exception) {
            alert('Error message.');
        }
    });
}
I tried it with a test array but no success. :( I also tried to set traditional: true, or contentType: 'application/json; charset=utf-8' but no success as 

well ...

The int[] useraccountIds posted to my controller is always null.


AVADHESH PATEL

Total Post:604

Points:4228
Posted on    April-03-2013 8:28 AM

Hi Manoj!

Try this way

$.ajax({
        traditional: true,
        url: target,
        type: "POST",
        data: { projectId: projectId, useraccountIds: JSON.stringify(new Array(1, 2, 3)) },
        success: ajaxOnSuccess,
        error: function (jqXHR, exception) {
            alert('Error message.');
        }
    });

Don't want to miss updates? Please click the below button!

Follow MindStick