Reputation: 51
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?
Upvotes: 1
Views: 1059
Reputation: 218892
Since it is a complex object, specify the content type as application/json and send the data as stringified json string.
$.ajax({
type: 'POST',
url: url,
contentType: 'application/json',
data: JSON.stringify(user),
success: function (event) {
// do something
},
error: function (xhr, status, error) {
alert("You didn't do it right.");
}
});
Now model binder will be able to map the data sent from the ajax call to the corresponding properties
Also assuming your properties are settable.
public class User
{
public string FirstName { set; get; }
public string LastName { set; get; }
public List<Friend> Friends { set; get; }
}
public class Friend
{
public string NickName { set; get; }
public string FirstMetLocation { set; get; }
}
Upvotes: 1