Neil N
Neil N

Reputation: 25258

Nested JSON values not binding MVC

I have a game object in client side JavaScript that looks like this right before being sent to the server:

Client Side

Here it is server side a second later, note all the properties are filled, and the Questions list is populated with the correct number of question, however the properties of each question are null, whereas on the client side they had the correct values.

Server Side

Here is the code for the models:

public class Game
{
    public Game()
    {
        Questions = new List<Question>(5);
    }
    public int GameID { get; set; }
    public Guid UserID { get; set; }
    public Guid CurrentGameID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public IEnumerable<Question> Questions { get; set; }
}

public class Question
{
    public int ID { get; set; }
    public string Text { get; set; }
    public IEnumerable<int> Answers { get; set; }
    public int SelectedAnswer { get; set; }
}

And here is how I send the object back to the server:

// Send completed game back to server
$.post("Games/CompleteGame", currentGame, function (results)
{
    // display results to user
}

Upvotes: 1

Views: 1504

Answers (1)

Neil N
Neil N

Reputation: 25258

Based on Ek0nomik's comment asking about the content-type, I rewrote my ajax call to set contentType to json:

$.ajax(
    {
        url: "Games/CompleteGame",
        type: "POST",
        data: JSON.stringify(currentGame),
        contentType: "application/json",
        success: function (results)
        {
            // show results to user...
        }

As it turns out, this was all it needed to make it work.

Upvotes: 1

Related Questions