Post JavaScript array with AJAX to asp.net MVC controller

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 JavaScript 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.

Answers:

Answer

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

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
}
Answer

Using $.Ajax(), you can easily get the data from javascript to the Controller in MVC.

As like,

var uname = 'John Doe';

$.ajax({

        url: "/Main/getRequestID",  // This is path of your Controller with Action Result.
        dataType: "json",           // Data Type for sending the data

        data: {                     // Data that will be passed to Controller
            'my_name': uname,     // assign data like key-value pair       
             // 'my_name'  like fields in quote is same with parameter in action Result
        },

        type: "POST",               // Type of Request
        contentType: "application/json; charset=utf-8", //Optional to specify Content Type.

        success: function (data) { // This function is executed when this request is succeed.
                alert(data);
        },

        error: function (data) {
                alert("Error");   // This function is executed when error occurred.
        }
)};

then, on the Controller side,

public ActionResult getRequestID(String my_name)
{

    MYDBModel myTable = new Models.MYDBModel();
    myTable.FBUserName = my_name;
    db.MYDBModel.Add(myTable);
    db.SaveChanges();              // db object of our DbContext.cs
    //return RedirectToAction(“Index”);   // After that you can redirect to some pages…
    return Json(true, JsonRequestBehavior.AllowGet);    // Or you can get that data back after inserting into database.. This json displays all the details to our view as well.
}

Reference. Send Data from Java Script to Controller in MVC

Answer

if you want to pass an array to mvc engine, send the input multiple times. change your code to the following :

function sendForm(projectId, target) {
var useraccountIds = new Array(1, 2, 3);
var data = { projectId: projectId };
for (var i = 0; i < useraccountIds.length; i++) {
  $.extend(true, data, {useraccountIds: useraccountIds[i]});
}
$.ajax({
    traditional: true,
    url: target,
    type: "POST",
    data: data,
    success: ajaxOnSuccess,
    error: function (jqXHR, exception) {
        alert('Error message.');
    }
});

}

Answer

Put the serializable attribute on the class. Then it will try to convert the javascript object you are passing to the C# class.

in JS:

{
   ProjectId = 0, 
   userAccountIds = []
}

// C#
[Serializable] 
public class AddUserViewModel
{
    public int ProjectId { get; set; }
    public int[] userAccountIds { get; set; }
}
Answer

It won't work unless you specify that the ajax request (Post/Get) has the property traditional is set to true. Please refer to this question for more details.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.