0

Why doesnt 3 level nesting model binding from json work?

Testing with 2 levels, say adding a string property on LevelTwo, works, but 3 levels doesnt? Is this by design, a bug, or am I missing something?

Client side jQuery post:

    $.ajax({
        url: "MyController/MyAction",
        dataType: "json",
        type: "POST",
        cache: false,
        data: {
            Level1: {
                Level2: {
                    StringValue: "Test"
                }
            }
        }
    });

Server side model:

public class MyForm
{
    public LevelOne Level1 { get; set; }
}

public class LevelOne
{
    public LevelTwo Level2 { get; set; }
}

public class LevelTwo
{
    public string StringValue { get; set; }
}

1 Answer 1

1

Why doesnt 3 level nesting model binding from json work

You are not sending any JSON to the server. If you want to send a JSON request here's how:

$.ajax({
    url: "MyController/MyAction",
    contentType: 'application/json; charset=utf-8',
    dataType: "json",
    type: "POST",
    cache: false,
    data: JSON.stringify({ 
        Level1: { 
            Level2: { 
                StringValue: "Test" 
            } 
        } 
    })
});

The JSON.stringify method is what serializes the javascript literal into a JSON string. It is natively built in modern browsers. If you need to support legacy browsers you could include the json2.js script to your page.

Sign up to request clarification or add additional context in comments.

3 Comments

Doh! Thanks! I assumed that dataType: "json" was all that was needed. You know, assumptions is the mother of all...
@MatteS, dataType: 'json' indicates the response content type, not the request. Also if your server sends proper Content-Type response header to application/json you don't even need it as jQuery will automatically infer it. You can omit this parameter from your ajax request.
Yes. This made me go back and recall why the dataType option was added to begin with in our code base, and it might be worth noting that it adds the header "Accept:application/json, text/javascript, /;" to the request, and thats something our error handling logic likes.

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.