I’m trying to pass a collection of objects to the controller using $.post(); When I call the AddNewPerson() the C# side Friends collection has the right number of objects in it, but the properties are all blank.
Javascript:
function AddNewPerson(newPerson) {
$.post("/Person/AddPerson/",
{
PersonName: newPerson.PersonName,
PersonAge: newPerson.PersonAge,
Friends:FriendList
},
function (JsonResponse) {
});
}
C#
public JsonResult AddPerson(Person newPerson)
{
Database.Add(newPerson);
}
Friends is a collection of Person
Javascript
function Person(Name, Age) {
this.PersonName=Name;
this.Person.Age=Age;
this.FriendList=new Array();
}
C#
public class Person()
{
public Person()
{
}
public string PersonName{get;set;}
public string PersonAge{get;set;}
public Person[] Friends { get; set; }
}
You could use a JSON request when you want to send complex structures like this:
From your example it is not exactly clear how you are populating the
FriendListvariable that you are using but I guess it is something like this:The
JSON.stringifymethod shown here is natively built into modern browsers but if you want to support legacy browsers you will need to include the json2.js script to your page.