POST JAVASCRIPT ARRAY WITH AJAX TO ASP.NET MVC CONTROLLER

Manoj Bhatt

Total Post:154

Points:1086
Posted by  Manoj Bhatt
 6488  View(s)
Ratings:
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.
  1. AVADHESH PATEL

    Post:604

    Points:4228
    Re: Post JavaScript array with AJAX to asp.net MVC controller

    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.');
            }
        });

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!