21

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.

SharpC
  • 6,974
  • 4
  • 45
  • 40
mosquito87
  • 4,270
  • 11
  • 46
  • 77

6 Answers6

39

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.');
        }
    });
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Even a hardcoded projectId (like 23) isn't sent to the controller. Instead the real form data (there's a project id too) is sent. :( – mosquito87 Apr 03 '13 at 09:03
  • 1
    This `sendForm` function over there, where are you calling it? Is it in the submit event of some form or the click event of some submit button? Did you make sure to cancel the default action of this event by returning false from it? I guess you haven't. – Darin Dimitrov Apr 03 '13 at 09:05
  • Hi, Is there anyway I could send javascript object to asp.net and get that class object in ApiController? – gayan1991 Mar 03 '15 at 19:04
18

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
}
Denis Besic
  • 3,067
  • 3
  • 24
  • 35
2

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

Shiva
  • 20,575
  • 14
  • 82
  • 112
Nikhil Prajapati
  • 944
  • 1
  • 12
  • 30
  • Thanks Josh for updating me.. I have updated the link. please check. Actually i have moved my blog from Wordpress to blogger. So that link was broken. Now its working.. – Nikhil Prajapati Mar 30 '15 at 05:32
1

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

}

Reza Abolfathi
  • 3,061
  • 2
  • 18
  • 14
0

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; }
}
marko
  • 10,684
  • 17
  • 71
  • 92
0

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.

Community
  • 1
  • 1
Mostafa
  • 113
  • 13