1

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?

1 Answer 1

1

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; }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the response! I'll give this a go as soon as I can. My properties are settable. Is there a reason why the model binder can't handle complex objects the way I've done it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.