leora
leora

Reputation: 196891

How can i pass an array of objects from javascript to asp.net-mvc function through ajax?

I have the following javascript code that builds up an array of objects and i am trying to push this to an asp.net-mvc action through an ajax post. I am trying to figure out what is wrong with this below ?

javascript:

var arr = [];
for (var i = 0; i < 5; i++) {
     var obj = {
        statusId: i,
        resizeable: true,
        rows: [1, 2, 3, 4, 5]
      };
      arr.push(obj);
}

$.ajax({
   type: 'POST',
   traditional: true,
   url: '/MyController/UpdateMe',
   data { info: arr },
   success: function () {  
       alert("complete");
   }
});

C# asp.net-mvc action:

public ActionResult UpdateMe(IEnumerable<UpdateInfo> info)
{
     foreach (var item in info)
     {
          Console.Write(item.statusIs + " has + " item.rows.length() + " items ");
     }
}

public class UpdateInfo
{
    public int statusId {get;set;}
    public bool resizable {get;set;}
    public List<int> rows {get;set;}
}

Upvotes: 1

Views: 2635

Answers (2)

cryptochronoconolite
cryptochronoconolite

Reputation: 101

You cannot pass a JS array as a parameter in a POST request. You have to turn it into a string to pass it to the .NET action. Consider using jQuery.param() to do this. It will convert the object to a string like statusId=valueOfI&resizeable=true. Then you change it from a string back to an array after you receive it in the action (I can't suggest a function since I don't know .NET).

Upvotes: 0

alexmac
alexmac

Reputation: 19617

By default jQuery.ajax contentType is application/x-www-form-urlencoded. This means that parameters sent in url string. In your case, your array transformed to string: object&object&object.....

To change this behavoir, you should change contentType in jQuery.ajax to application/json and convert your js object to json with JSON.stringify:

$.ajax({
   type: 'POST',
   traditional: true,
   contentType: 'application/json',
   url: '/SchoolDetails/UpdateMe',
   data: JSON.stringify({ info: arr }),
   success: function () {  
      alert("complete");
   }
});

Action in debug:

enter image description here

Upvotes: 3

Related Questions