I have a need to databind a JSON object, where the receiving model has a list of another model. Example:
public class User
{
public string FirstName;
public string LastName;
public List<Friend> Friends;
}
Friend class:
public class Friend
{
public string NickName;
public string FirstMetLocation;
}
I need to build a JSON object that databinds to the User model when I call an action.
The way I'm building my JSON object is like so:
var friends = [];
// iterate over something and add friend object to array
friends.push({
NickName: 'Bongos',
FirstMetLocation: 'That place'
});
var user = {
FirstName: 'Joe',
LastName: 'Somebody',
Friends: friends
};
That ends up producing JSON like so:
{"FirstName":"Joe","LastName":"Somebody","Friends":[{"NickName":"Bongos","FirstMetLocation":"That place"}]}
I'm then passing it on to my action through an AJAX POST:
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: user,
success: function (event) {
// do something
},
error: function (xhr, status, error) {
alert("You didn't do it right.");
}
});
When it gets to action the User object picks up the FirstName and LastName properties, but the List<Friend> is null. When I strip it down to just passing in a List<Friend> It works fine. That JSON looks like so:
{"Friends":[{"NickName":"Bongos","FirstMetLocation":"That place"}]}
Am I missing something?